Java 使用Scanner.next()将两个参数从txt文件传递给对象两次。结果:";“未知来源”;

Java 使用Scanner.next()将两个参数从txt文件传递给对象两次。结果:";“未知来源”;,java,file,arraylist,Java,File,Arraylist,我有一个包含一些数据的文本文件,用空格分隔 我有一个构造函数,它接受两种类型的数据: constructor(short members, int income){ this.members = members; this.income = income; } 我想要完成的是,一下子,将第一个数字作为短数字传递给一个对象,将第二个数字作为int传递给一个对象 我的文本文件类似于以下内容: 1 22229 2 27674 3 34022 4 41307 5 46850 6 528

我有一个包含一些数据的文本文件,用空格分隔

我有一个构造函数,它接受两种类型的数据:

constructor(short members, int income){
    this.members = members;
    this.income = income;
}
我想要完成的是,一下子,将第一个数字作为短数字传递给一个对象,将第二个数字作为int传递给一个对象

我的文本文件类似于以下内容:

1 22229
2 27674
3 34022
4 41307
5 46850
6 52838
7 58827
public static void main (String[] args) throws IOException {

        Scanner fileScan;

        fileScan = new Scanner (new File("survey.txt"));


        List<Household> houseList = new ArrayList<Household>();

        while (fileScan.hasNext()) {
            System.out.println(fileScan.nextLine());

            /*
            houseList.add(new Household((short) fileScan.nextInt(),
                    fileScan.nextInt()));
            */
        }

        for (int i = 0; i < houseList.size(); i++) {
            System.out.println(houseList.get(i).toString());
        }
    }
我的代码类似于:

1 22229
2 27674
3 34022
4 41307
5 46850
6 52838
7 58827
public static void main (String[] args) throws IOException {

        Scanner fileScan;

        fileScan = new Scanner (new File("survey.txt"));


        List<Household> houseList = new ArrayList<Household>();

        while (fileScan.hasNext()) {
            System.out.println(fileScan.nextLine());

            /*
            houseList.add(new Household((short) fileScan.nextInt(),
                    fileScan.nextInt()));
            */
        }

        for (int i = 0; i < houseList.size(); i++) {
            System.out.println(houseList.get(i).toString());
        }
    }
如果我将任一项单独传递给对象,它将运行,但在两次使用nextInt()时,会出现“未知源”错误

如果有一种方法可以使这项工作,或者有一种方法可以获得这种效果,我将非常感谢您的帮助

谢谢,如果这个问题已经回答了,很抱歉。

试试看

while (fileScan.hasNextLine()) {
        String[] temp = fileScan.nextLine().split(" ");
        if (temp.length == 2){
            houseList.add(new Household(Short.parseShort(temp[0]),
            Integer.parseInt(temp[1])));
        }
    }

在读入一行后检查得到的内容(如果可以,请使用调试器,或打印语句)。我想这会让你找到正确的方向。您第一次读取该文件将得到“12324”,但我认为您期望的是“1”。@user您是否使用默认参数实例化扫描仪?您能验证您的文件只包含两个整数的行(或空行)吗?是的,我要做的是传递“1”,然后传递“2324”。这就是我在创建新对象时两次使用fileScan.nextInt()的逻辑。因为它不喜欢多次调用.next(),所以最好的方法是获取.nextLine(),然后将其分成两个变量,并将其从这些变量传递给对象@kiruwka文件包含多行,每行有两个整数。我将把扫描器实例添加到OP中的代码中。HasNext将为您提供全部内容。你需要想出一些其他的方法。用逗号将值分隔在一行(或在空格上拆分,但这总是让我紧张),然后拆分它们,诸如此类。谢谢!这正是我想要的。。。只是我一个人想不起来。非常感谢您的及时帮助!所有人!作为另一种解决方案,在尝试了这一点之后,我只是以不同的方式组织了我的.txt文件(用新行分隔,而不是用新行和空格分隔),并使用了nextInt()等方法。