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++;
	}
}

Recommended Answers

All 2 Replies

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, ...);

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.