gpt4 book ai didi

Java - 字符串无法转换为int

转载 作者:行者123 更新时间:2023-11-30 02:47:50 24 4
gpt4 key购买 nike

我有一个包含所有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com