将对象放入ArrayList时显示NoSuchElementException

问题描述 投票:0回答:1

我试图通过从文件中读取名称和密码并将它们放入ArrayList中的对象中,从而将对象放入数组列表中,当我这样做时,它会给我NoSuchElementException有人可以解释为什么会这样吗?

public static ArrayList<ArrayListPractice> getUsersToArrayList(ArrayList<ArrayListPractice> Users) {
    try {
        File fin = new File("UserCreation.txt");
        FileInputStream fr = new FileInputStream(fin);
        Scanner sc = new Scanner(fr);

        while (sc.hasNext()) {
            String tempName = sc.next();
            String tempPass = sc.next();
            ArrayListPractice User = new ArrayListPractice(tempName, tempPass);

            Users.add(User);
            printUsersArrayList(Users);
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Users;
}
java arraylist nosuchelementexception
1个回答
0
投票

这看起来不正确:

while (sc.hasNext()) {
   sc.next();
   sc.next();
}

hasNext()调用保证至少存在one个元素供您读取,但不能两个。您对next()的第二次呼叫正在做出危险的假设。

类似,您的namepassword字符串都被读入tempName变量。由于没有剩余要读取的元素,因此在第二次调用next()时会引发异常。

© www.soinside.com 2019 - 2024. All rights reserved.