java - 异常和文件 I/O

标签 java exception file-io null average

大家好,我需要帮助,当我运行代码时,它会输出以下内容:

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/

相关文章:

java - 如何设置文件输入流的路径

c++ - 我如何更恰本地将异常集成到我的代码和 future 的代码中? (C++)

尝试读取文件并在出现异常时回退到备用文件的 Pythonic 方式

postgresql - 在 plpgsgl 异常处理程序中获取违反的 fk 的名称

java - 使用 FileInputStream 从文件中读取文本

javascript - 在nodejs中使用wait.for暂停非阻塞文件读取

java - 如何改变jsp中的url模式

java - 在方法类型参数列表或方法参数中定义有界类型参数

c# - 处理和合并两个大文件

java - 两个不同的 jar x,y 依赖于不同版本的 z。用户如何在他的应用程序中同时拥有 x,y ?