I'm programming a game and in the program I need to add new enemies based off of a file. Right now my problem is that I've run into an infinite while loop when trying to read this file. I'm relatively new to programming so I'm not exactly sure how to fix this. Here is the problem code. An example of how the entry in the file looks is: "Troll,6,4,1". Thank you for your help.
try {
Scanner input = new Scanner(new File(filename));
while(input.hasNext());
{
input.useDelimiter(",|\n");
String name = input.next();
int strength = input.nextInt();
int speed = input.nextInt();
int numVials = input.nextInt();
Enemy newEnemy = new Enemy(name, strength, speed, numVials);
opponents.add(newEnemy);
input.close();
}
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
The infinite loop is being caused because of the ;
after your while
statement. Also I believe there is a logic related issue with your code. We can read each line of the file, then split the each line based on the ',' by using the following code :
String line[];
do {
line = input.next().split(",");
String name = line[0];
int strength = Integer.parseInt(line[1]);
int speed = Integer.parseInt(line[2]);
int numVials = Integer.parseInt(line[3]);
Enemy newEnemy = new Enemy(name, strength, speed, numVials);
opponents.add(newEnemy);
input.close();
} while (input.hasNext());