我一直在编写这段代码,但它给了我错误。根据我的理解,他们看起来不错。
文本文件是:
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。
发布于 2013-10-15 12:24:23
此语句将在第二次迭代结束时抛出一个NoSuchElementException。
inFile.nextLine();如果没有剩下的线的话。你可以
if (inFile.hasNextLine()) {
inFile.nextLine();
}也在Product类中
this.company = name;应该是
this.company = company;发布于 2013-10-15 12:19:00
如果不使用"PrintStream“对象,为什么要声明它?嗯,Scanner类有时会显示出使用同一个Scanner对象读取数字和字符串的问题。您可以创建一个用于读取数字- obj.nextInt() -和另一个用于读取字符串- obj2.nextLine() - =)
https://stackoverflow.com/questions/19380892
复制相似问题