0

I am having problems reading in from a file in my project. I have a text file from which I need to read in data for creating some objects. I do not know how much data is in the file but I know the format is 6 lines of string, string, float, float, int, int. Everything works fine if I only have one entry in the text file but my program dies if there are any more. What can I do?

while(dataFile.hasNextLine() && numPlayers < 10)			
	{
		good = true;
		Player temp = new Player(dataFile.nextLine(), dataFile.nextLine(), dataFile.nextFloat(), dataFile.nextFloat(), dataFile.nextInt(), dataFile.nextInt());
	if(temp.getMoney() > 0)
	{
		thePlayers[numPlayers] = temp;
		numPlayers++;
	}
}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by BestJewSinceJC
0

this is asking for disaster

Player temp = new Player(dataFile.nextLine(), dataFile.nextLine(), dataFile.nextFloat(), dataFile.nextFloat(), dataFile.nextInt(), dataFile.nextInt());

separate that out and find out where its messing up
example

String str1 = dataFile.nextLine();
String str2 = dataFile.nextLine();
//....
Player temp = new Player(str1, str2, ...);
0

Its because hasNextLine() will return true if there is a next line, even if that line does NOT contain any information. In other words, if there is a newline character, hasNextLine() will return true. Whereas hasNext() will only return true if there is a next token. A token is defined as anything that is preceded and followed by the delimiter pattern, (which is whitespace by default). In other words, change it to hasNext() and it will work. Also, read this...


http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#hasNext()

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.