Java - 字符串不能转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39638851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - String cannot be converted to int
提问by Jonny Birkebeiner
I have a textfile with temperatures from all 12 months. But when I try to find the average temperature, I get the error "String cannot be converted to int" to the line
我有一个包含所有 12 个月温度的文本文件。但是当我试图找到平均温度时,我收到错误“字符串无法转换为整数”到该行
temp[counter] = sc.nextLine();
temp[counter] = sc.nextLine();
Can someone say what's wrong?
有人可以说有什么问题吗?
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);
采纳答案by Dsenese1
You need to convert sc.nextLineinto int
您需要将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);
}
}
回答by DaImmi
Scanner::nextLine returns a String. In Java you can't cast a String to an int like you do implicitly.
Scanner::nextLine 返回一个字符串。在 Java 中,您不能像隐式那样将 String 转换为 int。
try
尝试
temp[counter] = Integer.parseInt(sc.nextLine());
回答by Johnny Five
Your sc.nextLine() returns String
你的 sc.nextLine() 返回 String
https://www.tutorialspoint.com/java/util/scanner_nextline.htm
https://www.tutorialspoint.com/java/util/scanner_nextline.htm