【发布时间】:2017-07-12 00:50:25
【问题描述】:
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。
无论如何我可以让阵列在扫描仪中接受这两种类型的数字,还是我必须采用另一种工作方式?
【问题讨论】:
-
正常情况是将所有内容都视为
double。您可以毫无问题地将 236 存储在double中。为什么将其保留为整数很重要?将其保留为双精度会有什么不良后果? -
另外,
InputMismatchException发生在这条线上:personsWeight[i] = scnr.nextInt();,与数组类型无关。它与在其中包含小数的输入上使用nextInt()有关。
标签: java arrays printing int double