0

当我尝试从文件中读取信息以创建对象时,我收到了 NoSuchElementException。谁能帮我看看出了什么问题?

else if(response == 3){
    System.out.println("Enter the name of the file to load items from: ");
    loadFile = input.nextLine();
    try {
        infile = new Scanner(new FileReader(loadFile+".txt"));
    }
    catch(IOException err) {
        infile = null;
        System.out.println("Cannot open file\n");
    }
    while(infile.hasNext()){
        itemType = infile.next();
        name = infile.next();
        itemDescription = infile.next();
        itemCalories = infile.nextInt();
        itemPrice = infile.nextDouble();
        itemSpecific = infile.nextLine();
        createNewObject(counter, itemType, name, itemDescription, itemCalories, itemPrice, itemSpecific);
    }
}

我的文件“项目”安排如下:

甜甜圈                                  
果冻甜甜圈                        
带糖霜的圆形                             
100                                  
1.22                                  
奶油填充                                
4

1 回答 1

2

hasNext()只检查一次,然后不检查就得到一堆令牌。那很危险。每个都nextXXX()应该以hasNextXXX().

于 2014-02-08T02:03:15.650 回答