如何解决nextLine NoSuchElementException异常()? [英] how to solve NoSuchElementException with nextLine()?
本文介绍了如何解决nextLine NoSuchElementException异常()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在写这个code,但它给我的错误。根据我的了解,他们看起来虽好。
I have been writing this code but it gives me error. based on my understanding, they looks good though.
该文本文件是:
2
Galaxy
Samsung phone
2.99
iPhone
Apple phone
3.99
在code是:
public class IO {
static final String FILE_LOCATION = "C:\\IO.dat";
static ArrayList<Product> productList = new ArrayList<Product>();
public static void main(String[]args){
File name = new File(FILE_LOCATION);
if(name.canRead())
System.out.println("Your file is ready to use");
Scanner inFile;
PrintStream ps;
try{
inFile = new Scanner(name);
int partNum;
String product;
String company;
double price;
partNum = inFile.nextInt();
inFile.nextLine();
for(int i=0; i<2 ; i++){
product = inFile.nextLine();
System.out.println(product);
company = inFile.nextLine();
System.out.println(company);
price = inFile.nextDouble();
System.out.println(price);
inFile.nextLine();
productList.add(new Product(product, company, price));
}
inFile.close();
}catch(FileNotFoundException e){
System.out.println("File is not good for use");
}
for(int i=0; i<productList.size(); i++){
System.out.println(productList.get(0));
}
}
}
产品类
public class Product {
String name;
String company;
double price;
public Product(String name, String company, double price) {
this.name = name;
this.company = name;
this.price = price;
}
public String toString() {
return name + " " + company + " " + price;
}
}
当我要求从ArrayList中打印,它给了我像银河星系2.99
,而不是银河三星手机,2.99
。
When I ask for print from ArrayList, it gives me like Galaxy Galaxy 2.99
rather than Galaxy Samsung phone, 2.99
.
推荐答案
这声明将在第二迭代结束时抛出一个 NoSuchElementException异常
This statement will throw a NoSuchElementException
at the end of the second iteration
inFile.nextLine();
如果没有剩余的多个行。你可以做
if there are no more lines remaining. You could do
if (inFile.hasNextLine()) {
inFile.nextLine();
}
另外在产品
类
this.company = name;
应
this.company = company;
这篇关于如何解决nextLine NoSuchElementException异常()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文