Java Scanner类读取一行然后停止

时间:2013-08-08 19:19:26

标签: java

使用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)

3 个答案:

答案 0 :(得分:8)

我猜测Integer.ParseInt()正在抛出NumberFormatException,因为您的行仍然包含\n

如果您拨打Integer.ParseInt(text.trim()),则可以解决此问题。

如果您正确处理了Exception,我们会有更好的主意。

答案 1 :(得分:0)

这是因为,在解析整数时,你有一个NumberFormatException。

添加类似这样的catch部分

System.out.println(e.getCause());

看,你有一个例外,这就是为什么这个代码只打印第一个数字。

答案 2 :(得分:0)

使用扫描仪时需要小心。

如果您正在阅读更多数据,使用Scaner,如input.nextInt();,那么它只会读取一个int。 {strong> nextInt不会消费回车。一种解决方案是添加input.nextLine();以便它移动到下一行。

其他解决方案是,我更喜欢使用 BufferedReader;

    BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
    String tempStr = bufferRead.readLine();

    // Do some operation on tempStr

希望这有帮助。