0

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

文本文件是:

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 打印时,它给了我 likeGalaxy Galaxy 2.99而不是Galaxy Samsung phone, 2.99.

4

2 回答 2

1

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

inFile.nextLine();

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

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

也在Product课堂上

this.company = name;

应该

this.company = company;
于 2013-10-15T12:24:23.500 回答
0

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

于 2013-10-15T12:19:00.117 回答