[英]Reading from a file problems
I am getting a NoSuchElementException when I am trying to read info from a file to create an object. 当我尝试从文件中读取信息以创建对象时,我收到NoSuchElementException。 Can anyone help me see what is going wrong? 谁能帮我看看出了什么问题?
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);
}
}
My file 'items' is arranged as so: 我的文件'items'排列如下:
Doughnut Jellydoughnut Roundwithfrosting 100 1.22 creamfilling
You're checking hasNext()
just once, and then getting a bunch of tokens without checking. 你只检查一次hasNext()
,然后在没有检查的情况下得到一堆令牌。 That's dangerous. 这很危险。 Each nextXXX()
should be preceded by a hasNextXXX()
. 每个nextXXX()
都应该以hasNextXXX()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.