本文介绍了如何使用 nextLine() 解决 NoSuchElementException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在编写这段代码,但它给了我错误.根据我的理解,它们看起来不错.
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
代码是:
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 打印时,它给我的是 Galaxy Galaxy 2.99
而不是 Galaxy Samsung phone, 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();
}
也在 Product
类中
this.company = name;
应该是
this.company = company;
这篇关于如何使用 nextLine() 解决 NoSuchElementException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!