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()'的輸入有關,它有一個小數。 –