Java 乘以用户输入集?

Java 乘以用户输入集?,java,Java,这个java练习希望我要求用户输入他们想要乘以n的值,然后让用户输入这些数字。之后,我应该乘以用户输入,这就是我被卡住的地方 到目前为止,我所拥有的: import java.util.Scanner; public class GeometricMean { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, i; St

这个java练习希望我要求用户输入他们想要乘以n的值,然后让用户输入这些数字。之后,我应该乘以用户输入,这就是我被卡住的地方

到目前为止,我所拥有的:

import java.util.Scanner;

public class GeometricMean {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n, i;
        String value;
        double product;
        System.out.println("Please enter how many numbers you want to process");
        n = sc.nextInt();
        for (i = 1; i <= n; i++) {
            System.out.println("Please enter a value");
            value = sc.nextLine();
        }
        product = (i * i);
        //If i did know what the correct product formula is I would write:
        System.out.println("The product is" + product);
    }
}

您当前未对输入执行任何操作。此外,您要乘以用户输入的数字量,而不是乘以实际数字

您可以首先创建一个数组,使用用户的输入指定索引的数量:

int n = scanner.nextInt();
double[] numbers = new double[n];
然后在数组中循环,接收每个索引的值:

for(int i = 0; i < numbers.length; i++)
     numbers[i] = sc.nextDouble();
尽管如此,当您收到以下号码时,只需将其添加到产品中会更容易:

int n = scanner.nextInt();
double product = 1.0;
for(int i = 0; i < n; i++) {
     product *= sc.nextDouble();
作为一个完整的应用程序,使用更简单的替代方案:

import java.util.Scanner;

public class GeometricMean {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter how many numbers you want to process");
        int n = sc.nextInt();

        double product = 1.0;
        for (i = 1; i <= n; i++) {
            System.out.println("Please enter a value");
            product *= sc.nextDouble();
        }
        System.out.println("The product is" + product);
    }
}

创建一个total变量并将其设置为1要容易得多。扫描每个值后,只需将输入与总计相乘,并将其分配给总计:总计=总计*输入;或total*=输入。在执行程序之前,应将乘积设置为1。之后,只需将其乘以值即可。product=product*value您应该将value设置为int,或者使用value=sc.nextInt,然后按照@HamZa所说的做。如果您有Java8,那么您可以使用Stream和reduce在一行中完成整个工作。
import java.util.Scanner;

public class GeometricMean {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter how many numbers you want to process");
        int n = sc.nextInt();

        double product = 1.0;
        for (i = 1; i <= n; i++) {
            System.out.println("Please enter a value");
            product *= sc.nextDouble();
        }
        System.out.println("The product is" + product);
    }
}