这是一个代码片段,显示我尝试写入文件。
public void printContents() {
int i = 0;
try {
FileReader fl = new FileReader("Product List.txt");
Scanner scn = new Scanner(fl);
while (scn.hasNext()) {
String productName = scn.next();
double productPrice = scn.nextDouble();
int productAmount = scn.nextInt();
System.out.println(productName + " is " + productPrice + " pula. There are " + productAmount + " items left in stalk.");
productList[i] = new ReadingAndWritting(productName, productPrice, productAmount);
i = i + 1;
}
scn.close();
} catch (IOException exc) {
exc.printStackTrace();
} catch (Exception exc) {
exc.printStackTrace();
}
}
public void writeContents() {
try {
//FileOutputStream formater = new FileOutputStream("Product List.txt",true);
Formatter writer = new Formatter(new FileOutputStream("Product List.txt", false));
for (int i = 0; i < 2; ++i) {
writer.format(productList[i].name + "", (productList[i].price + 200.0 + ""), (productList[i].number - 1), "\n");
}
writer.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
尝试运行此代码时抛出的异常是:
java.util.NoSuchElementException at ReadingAndWritting.printContents(ReadingAndWritting.java:37).
我尝试了很多东西,结果只是:&#34; cokefruitgushersAlnassma&#34;在文件中。我想要的是:
coke 7.95 10
fruitgushers 98.00 6
Alnassma 9.80 7
答案 0 :(得分:1)
问题似乎在
String productName = scn.next();
// Here:
double productPrice = scn.nextDouble();
// And here:
int productAmount = scn.nextInt();
在scn.next()
之后,在请求下一个元素(分别为double或int)之前,不要检查是否scn.hasNext()
。因此,要么您的文件不完整,要么没有您期望的确切结构,或者您在尝试处理那些不存在的数据之前错过了另外两项检查。
解决方案可能就像:
while (scn.hasNext()) {
String productName = scn.next();
if ( scn.hasNext() ) {
double productPrice = scn.nextDouble();
if ( scn.hasNext() ) {
int productAmount = scn.nextInt();
// Do something with the three values read...
} else {
// Premature end of file(?)
}
} else {
// Premature end of file(?)
}
}