gpt4 book ai didi

java - 如何使用 nextLine() 解决 NoSuchElementException?

转载 作者:行者123 更新时间:2023-12-01 14:00:24 25 4
gpt4 key购买 nike

我一直在编写这段代码,但它给了我错误。根据我的理解,它们看起来不错。

文本文件是:

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 手机,2.99

最佳答案

此语句将在第二次迭代结束时抛出 NoSuchElementException

inFile.nextLine();

如果没有剩余的行。你可以这样做

if (inFile.hasNextLine()) {
inFile.nextLine();
}

也在Product类中

this.company = name;

应该是

this.company = company;

关于java - 如何使用 nextLine() 解决 NoSuchElementException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19380892/

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