无法将用户输入传递给数组。

huangapple go评论78阅读模式
英文:

impossible to pass user's input to the array

问题

我正在尝试通过扫描器将用户输入传递给数组。目标是计算输入的平均值,这是代码:

public class pro {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        double[] str1 = new double[20];
        for (int i = 0; i < 20; i++) {
            str1[i] = scanner.nextDouble();
        }
        double average = Arrays.stream(str1).average().orElse(0.0);
        System.out.println("平均值是:" + average);
    }
}
英文:

I am trying to pass user's input to the array through a scanner. The goal is to make the average value of the inputs, this is the code:

public static void main(String args[]) {
	Scanner scanner = new Scanner(System.in);
	        double[] str1 = new int [20] ;
	        str1 = scanner.next.Double();
	        System.out.println(&quot;Average is: &quot; + Arrays.stream(str1).summaryStatistics().getAverage());
	    }

}

答案1

得分: 1

以下两个语句存在语法错误,因此代码无法编译通过:

double[] str1 = new int[20];
str1 = scanner.next.Double();

你需要将双精度数组声明为 double[] str1 = new double[20];

你需要以以下方式输入双精度值:scanner.nextDouble(); 由于 str1 是一个数组,我们不能直接将输入存储为 str1 = scanner.nextDouble();,否则你的程序将会在编译时报错:

类型不匹配:无法从 double 转换为 double[]

为了解决这个错误,我们需要将每个输入的值存储在特定的索引位置,例如 str1[0] = scanner.nextDouble();

以下是根据你的需求编写的工作代码(根据我从你的问题中理解的):

Scanner scanner = new Scanner(System.in);

double[] str1 = new double[20];

for (int i = 0; i < 20; i++) {
    str1[i] = scanner.nextDouble();
}
System.out.println("Average is: " + Arrays.stream(str1).summaryStatistics().getAverage());

我希望这能帮助你解决你遇到的错误。

英文:

Below 2 statements are having syntax error and because of this code will not compile:

double[] str1 = new int [20] ;
str1 = scanner.next.Double();

you need to declare double array as double[] str1 = new double[20];

you need to take the double value as input like this scanner.nextDouble(); and as str1 is array we can't store the input directly as str1 = scanner.nextDouble(); in that case your program will give compile time error

> Type mismatch: cannot convert from double to double[]

To resolve this error we need to store the value of every input at specific index like str1[0] = scanner.nextDouble();

Below is the working code as per your requirement(as I understand from your question):

Scanner scanner = new Scanner(System.in);

double[] str1 = new double[20] ;

for(int i = 0; i &lt; 20;i++) {
   str1[i] = scanner.nextDouble();        	
}
System.out.println(&quot;Average is: &quot; + Arrays.stream(str1).summaryStatistics().getAverage());

I hope it will help you resolve the error you're facing.

huangapple
  • 本文由 发表于 2020年9月30日 12:34:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64130936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定