这个问题在这里已有答案:
我试图从我的txt中提取一个只包含一个数字的int,但是我收到错误:线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“3”
我试图只使用.nextInt直接从txt文件中提取int,但是n0ot工作,所以相反,我试图从txt文件中提取数字作为字符串,然后将其转换为我的int码。
import java.io.File;
import java.util.Scanner;
class Scratch {
public static void main(String[] args) throws Exception{
Scanner highScoreScan = new Scanner(new File("wordgamehighscores.txt"));//This file just has one integer which is the highscore.
while (highScoreScan.hasNext()) {
String highScoreInt = highScoreScan.next();
int highScore= Integer.parseInt(highScoreInt);
System.out.println(highScore);
}
}
}
这是完整的错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "3"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:638)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Scratch.main(scratch.java:10)
你应该在parseInt
之前修剪空间
String highScoreInt = highScoreScan.next();
highScoreInt = highScoreInt.trim();
int highScore= Integer.parseInt(highScoreInt);