将文件中的对象添加到程序中 [英] Adding an object from file into program

查看:128
本文介绍了将文件中的对象添加到程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编程游戏,在程序中我需要根据文件添加新的敌人。现在我的问题是我在尝试读取此文件时遇到了无限循环。我对编程比较陌生,所以我不确定如何解决这个问题。这是问题代码。文件中条目的示例如下:Troll,6,4,1。感谢您的帮助。

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

这篇关于将文件中的对象添加到程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆