从文件中读取问题

时间:2014-02-08 01:59:17

标签: java nosuchelementexception

当我尝试从文件中读取信息以创建对象时,我收到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);
    }
}

我的文件'items'按如下方式排列:

Doughnut                                  
Jellydoughnut                        
Roundwithfrosting                             
100                                  
1.22                                  
creamfilling                                

1 个答案:

答案 0 :(得分:2)

您只需检查hasNext()一次,然后在不检查的情况下获取一堆令牌。这很危险。每个nextXXX()都应以hasNextXXX()开头。