import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_VALS = 5;
int [] personsWeight = new int[NUM_VALS];
int i = 0;
for (i = 0; i < NUM_VALS; ++i) {
System.out.print("Enter weight " + (i + 1) + ": ");
System.out.println();
personsWeight[i] = scnr.nextInt();
}
double sumVal = 0.0;
for (i = 0; i < NUM_VALS; ++i) {
sumVal = sumVal + personsWeight[i];
}
double avgVal = 0.0;
for (i = 0; i < NUM_VALS; ++i) {
avgVal = sumVal/NUM_VALS;
}
double maxVal = 0.0;
for (i = 0; i < NUM_VALS; ++i) {
maxVal = personsWeight[0];
if (maxVal < personsWeight[i]) {
maxVal = personsWeight[i];
}
}
System.out.println();
System.out.println(personsWeight[1] + " " + personsWeight[2] + " "
+ personsWeight[3] + " " + personsWeight[4] + " " + personsWeight[5]);
//I know that this can be cleaner but this is where the
//problem occurs with a InputMismatchException.
//I know it's caused by the double being introduced
//but don't know how to fix it.
System.out.println("Total weight: " + sumVal);
System.out.println("Average weight: " + avgVal);
System.out.println("Max weight: " + maxVal);
return;
}
}
的输入是如下: 236, 89.5, 142, 166.3, 93。如何在数组中接受并输出双精度和双精度数?
我想处理输入数字,就像输入数字一样。 Double或Int。
有无论如何,我可以让阵列接受这两种类型的数字在扫描仪或我不得不采取另一种方式,它的工作?
正常情况下,将所有内容视为“双”。你可以在没有问题的情况下将236存储在“double”中。为什么重要的是你把它作为一个整数?会有什么不必要的后果将其保持为双重? – ajb
另外,InputMismatchException发生在这一行:'personsWeight [i] = scnr.nextInt();'并且与数组类型无关。它与使用'nextInt()'的输入有关,它有一个小数。 –