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 から print を要求すると、Galaxy Galaxy 2.99ではなくlike が表示されGalaxy Samsung phone, 2.99ます。

4

2 に答える 2

0

使用していないのに、なぜ「PrintStream」オブジェクトを宣言するのですか? まあ、 Scanner クラスは、同じ Scanner オブジェクトで数値と文字列を読み取るときに問題を示すことがあります。数字を読み取るために1つを作成しobj.nextInt()、文字列を読み取るために別のものを作成できますobj2.nextLine()--=)

于 2013-10-15T12:19:00.117 に答える