Lucas Fray Burchardt
Lucas Fray Burchardt

Reputation: 409

Java Scanner class reads one line and then stops

I have this problem with a method using the Scanner class. I am reading my text file with Scanner and then parse the int into an array.

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();
    }
}

Heres the item.txt file:

1
1
2
3
4

I run the code and I get the following output:

1

I have tried using scanner.hasNextInt() and scaner.nextInt(); for this but then it won't print anything at all.

If I remove the parseInt part then the file will finish reading and all the numbers will be printed. Any ideas?

This the exception thrown:

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)

Upvotes: 0

Views: 1604

Answers (3)

JNL
JNL

Reputation: 4713

You need to be careful when you use the Scanner.

If you are reading more data, with Scaner like input.nextInt(); then it will read only one int. The carriage return isn't consumed by nextInt. One solution is that add input.nextLine(); so that it moves to the next line.

Other Solution is, which I prefer is to use BufferedReader;

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

    // Do some operation on tempStr

Hope this helps.

Upvotes: 0

Robadob
Robadob

Reputation: 5349

I'm guessing Integer.ParseInt() is throwing an NumberFormatException because your line still contains the \n.

If you call Integer.ParseInt(text.trim()) instead, it may fix it.

If you did your Exception handling properly, we would have a better idea.

Upvotes: 8

Mysterion
Mysterion

Reputation: 9320

This is because, you have a NumberFormatException, while parsing integer.

Add in catch section something like this

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

And see, that you have an exception, that's why this code prints only first digit.

Upvotes: 0

Related Questions