例外和文件I / O.

时间:2014-01-10 05:17:49

标签: 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;
            }
       }
 }

2 个答案:

答案 0 :(得分:2)

问题出在while循环中:

while (in.hasNext()){
   total += in.nextInt();
   count++;
}

此循环仅在hasNext返回false时退出,这意味着计数== 0&& in.hasNext将永远不会成真。可能,您希望循环只处理整数。

这可能会更好:

while (in.hasNextInt()){
   total += in.nextInt();
   count++;
}

当没有int时循环将结束 - 但是hasNext仍然为true,因为文件中可能有字母等。

答案 1 :(得分:0)

            while (in.hasNextInt()){
                total += in.nextInt();
                count++;
            }
            if(count==0 && in.hasNextInt() == false){
                    throw new IllegalArgumentException(asd + " does not have numeric data");
            }

是的,这很可能是它。试试吧!