gpt4 book ai didi

java - 读取文件问题

转载 作者:行者123 更新时间:2023-12-02 06:14:04 26 4
gpt4 key购买 nike

当我尝试从文件读取信息以创建对象时,出现 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()一次,然后在没有检查的情况下获得一堆 token 。那很危险。每个 nextXXX() 前面应该有一个 hasNextXXX()

关于java - 读取文件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21640952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com