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.txt");
Scanner scanner = new Scanner(file);
int line = 0;
while (scanner.hasNextLine())
{
String text = scanner.nextLine();
text = text.replaceAll("\\W", "");
System.out.println(text);
PlayerInstance.playerItems[line] = Integer.parseInt(text);
line++;
}
scanner.close();
} catch (FileNotFoundException e)
{
} catch (NumberFormatException e2)
{
}
}
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)
No comments:
Post a Comment