Adding an object from file into program

后端 未结 3 1467
死守一世寂寞
死守一世寂寞 2021-01-26 14:23

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 14:50

    input.hasNext() does not move the pointer to the next line.

    After you call hasNext() the first time, if you don't read from the file, hasNext() will always return true. Because the front of the input doesn't change.

    Try this:

    try {
            Scanner input = new Scanner(new File(filename));
            String x = null;
    
            while((x = input.next()) != null)
            {
            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();
        }
    

提交回复
热议问题