我在使用 Scanner 类的方法时遇到了这个问题。我正在使用 Scanner 读取文本文件,然后将 int 解析为数组。
public static void readItems()
{
try
{
File file = new File(System.getProperty("user.home") + "./SsGame/item.dat");
Scanner scanner = new Scanner(file);
int line = 0;
while (scanner.hasNextLine())
{
String text = scanner.nextLine();
text = text.replaceAll("\\W", "");
System.out.println(text.trim());
PlayerInstance.playerItems[line] = Integer.parseInt(text);
line++;
}
scanner.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (NumberFormatException e2)
{
e2.printStackTrace();
}
}
这是 item.txt 文件:
1
1
2
3
4
我运行代码并得到以下输出:
1
我尝试过使用scanner.hasNextInt()和scaner.nextInt();为此,但它根本不会打印任何内容。
如果我删除 parseInt 部分,那么文件将完成读取并打印所有数字。有什么想法吗?
这是抛出的异常:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at game.player.ReadPlayer.readItems(ReadPlayer.java:56)
at game.player.ReadPlayer.read(ReadPlayer.java:11)
at game.Frame.<init>(Frame.java:32)
at game.Frame.main(Frame.java:54)
最佳答案
我猜测 Integer.ParseInt()
正在抛出 NumberFormatException
因为您的行仍然包含 \n
。
如果您改为调用 Integer.ParseInt(text.trim())
,它可能会修复它。
如果您正确处理异常
,我们会有更好的主意。
关于Java Scanner 类读取一行然后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18134294/