我一直在写这段代码,但它给了我错误。根据我的理解,它们看起来不错。
文本文件是:
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
.