如何使用nextLine()解决NoSuchElementException?

时间:2013-10-15 12:10:20

标签: java file-io input arraylist

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

文本文件是:

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

2 个答案:

答案 0 :(得分:1)

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

inFile.nextLine();

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

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

同样在Product班级

this.company = name;

应该是

this.company = company;

答案 1 :(得分:0)

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