首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用NoSuchElementException ()来解决NoSuchElementException问题?

如何用NoSuchElementException ()来解决NoSuchElementException问题?
EN

Stack Overflow用户
提问于 2013-10-15 12:10:19
回答 2查看 252关注 0票数 0

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

文本文件是:

代码语言:javascript
复制
2
Galaxy
Samsung phone
2.99
iPhone
Apple phone
3.99

守则是:

代码语言:javascript
复制
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));
                }
    }
}

产品类

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-15 12:24:23

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

代码语言:javascript
复制
inFile.nextLine();

如果没有剩下的线的话。你可以

代码语言:javascript
复制
if (inFile.hasNextLine()) {
    inFile.nextLine();
}

也在Product类中

代码语言:javascript
复制
this.company = name;

应该是

代码语言:javascript
复制
this.company = company;
票数 1
EN

Stack Overflow用户

发布于 2013-10-15 12:19:00

如果不使用"PrintStream“对象,为什么要声明它?嗯,Scanner类有时会显示出使用同一个Scanner对象读取数字和字符串的问题。您可以创建一个用于读取数字- obj.nextInt() -和另一个用于读取字符串- obj2.nextLine() - =)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19380892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档