大家好,我需要帮助,当我运行代码时,它会输出以下内容:
Average = 49.91791791791792
null
empty.txt is empty
Error: notThere.txt (No such file or directory)
Average = 0.0
但我的目标是让它输出:
Average = 49.91791791791792
squeeze.txt does not have numeric data
empty.txt is empty
Error: notThere.txt (No such file or directory)
Average = 0.0
我在理解作业的这一步时遇到问题: 在scanDataAndCalculateAverage方法中抛出以下异常 文件为空。 文件包含非数字数据。您可以假设数据文件中没有混合非数字和数字数据。这是通过检查是否读入了某些内容但计数为 0 来完成的。
你们能帮帮我吗?这是代码:http://pastebin.com/33WCBxEf
public class Average {
long total = 0;
int count = 0;
String asd = "";
public Average(String a){
asd = a;}
public double scanDataAndCalculateAverage(){
try {
FileReader f = new FileReader(asd);
Scanner in = new Scanner(f);
while (in.hasNext()){
total += in.nextInt();
count++;
}
if(count==0 && in.hasNext() == true){
throw new IllegalArgumentException(asd + " does not have numeric data");
}
if(count == 0 && total == 0){
throw new ArithmeticException(asd + " is empty");
}
return (double)total/count;
} catch (IOException e){
System.out.println("Error: " + e.getMessage());
return 0;
}
}
}
最佳答案
问题出在 while 循环中:
while (in.hasNext()){
total += in.nextInt();
count++;
}
仅当 hasNext 返回 false 时,此循环才会退出,这意味着 count==0 && in.hasNext 永远不会为 true。也许,您希望循环只处理整数。
这可能会更好:
while (in.hasNextInt()){
total += in.nextInt();
count++;
}
当没有 int 时循环将结束 - 但 hasNext 仍然为 true,因为文件中可能有字母等。
关于java - 异常和文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21036671/