我有一个包含所有 12 个月温度的文本文件。 但是当我尝试查找平均温度时,我收到错误“String无法转换为int”行
temp[counter] = sc.nextLine();
谁能告诉我这是怎么回事吗?
Scanner sc = new Scanner(new File("temperatur.txt"));
int[] temp = new int [12];
int counter = 0;
while (sc.hasNextLine()) {
temp[counter] = sc.nextLine();
counter++;
}
int sum = 0;
for(int i = 0; i < temp.length; i++) {
sum += temp[i];
}
double snitt = (sum / temp.length);
System.out.println("The average temperature is " + snitt);
最佳答案
您需要将sc.nextLine转换为int
Scanner sc = new Scanner(new File("temperatur.txt"));
int[] temp = new int [12];
int counter = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
temp[counter] = Integer.ParseInt(line);
counter++;
}
int sum = 0;
for(int i = 0; i < temp.length; i++) {
sum += temp[i];
}
double snitt = (sum / temp.length);
System.out.println("The average temperature is " + snitt);
}
}
关于Java - 字符串无法转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39638851/