繁体   English   中英

从文件中读取问题

[英]Reading from a file problems

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

你只检查一次hasNext() ,然后在没有检查的情况下得到一堆令牌。 这很危险。 每个nextXXX()都应该以hasNextXXX()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM