how to solve NoSuchElementException with nextLine(

2019-08-27 11:00发布

I have been writing this code but it gives me error. based on my understanding, they looks good though.

The text file is:

2
Galaxy
Samsung phone
2.99
iPhone
Apple phone
3.99

The code is:

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));
                }
    }
}

Product class

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;
    }
}

When I ask for print from ArrayList, it gives me like Galaxy Galaxy 2.99 rather than Galaxy Samsung phone, 2.99.

2条回答
霸刀☆藐视天下
2楼-- · 2019-08-27 11:17

Why are you declaring a "PrintStream" object if you're not using it? Well, the Scanner class sometimes shows problems to read numbers and strings with the same Scanner Object. You could create one to read numbers - obj.nextInt() - and another to read the Strings - obj2.nextLine() - =)

查看更多
【Aperson】
3楼-- · 2019-08-27 11:37

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();
}

Also in the Product class

this.company = name;

should be

this.company = company;
查看更多
登录 后发表回答