Adding an object from file into program

送分小仙女□ 提交于 2019-12-02 08:52:47

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

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

You have written : while(input.hasNext());

You need to remove the semi colon first.

Next you have closed the input within the loop that also needs to be done outside the loop as after the first time the input being closed will not get processed and will give exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!