需要帮助查找平均值并打印出错误

时间:2015-01-05 01:14:59

标签: java exception-handling

我需要帮助解决这个学校的问题。如果您有兴趣,请点击此链接:http://go.code-check.org/codecheck/files/14121519036ltx4u6e3i9mtrqynsyhgihr7

当我尝试解决问题时,我打印出正确的消息,但是有问题。我怀疑Codecheck的驱动程序是类似System.out.println(“Average =”+ message);或类似的东西。所以,我最终会得到一个结果

Average = squeeze.txt没有数字数据

这不是我想要的。如果司机给我这个问题,我该如何解决?这就是我目前所拥有的:

import java.io.*;

import java.util.*;

public class Average {

    double total = 0;
    int count = 0;
    Scanner in;
    String myName;
    public Average(String name){
        myName = name;
        try{
            in = new Scanner(new File(name));
        }
        catch (Exception e){
            System.out.println("Error: " + myName + " (The system cannot find the file specified)");
        }
    }

    public String scanDataAndCalculateAverage(){
        try{
            if (!in.hasNext())
                throw new Exception(myName + " is empty");
            else 
                while (in.hasNextLong()){
                    total += in.nextLong();
                    count++;
                }
            if (in.hasNext()){
                throw new Exception(myName + " does not have numerical data");
            }
            else return "" + (total / count);
        }
        catch (Exception e){
            return e.getMessage();
        }
    }

}

编辑:我的新构造函数:

public Average(String name)抛出异常{

    myName = name;
    try{
        in = new Scanner(new File(name));
    }
    catch (Exception e){
        throw new Exception("Error: " + myName + " (No such file or directory)");
    }
}

2 个答案:

答案 0 :(得分:0)

看起来输入文件包含的内容不是有效的。看到你有这些行:

while (in.hasNextLong()){
    total += in.nextLong(); 
    count++;
}
if (in.hasNext()){
    throw new Exception(myName + " does not have numerical data");
}

因此,如果您的文件与long不同,您将退出循环,然后if会向您发送您发布的消息。

要查找导致问题的确切因素,请更改此行:

throw new Exception(myName + " does not have numerical data");

到此:

throw new Exception(myName + " does not have numerical data: (" + in.next() + ")");

答案 1 :(得分:0)

您的代码存在以下问题:

catch (Exception e) {
    return e.getMessage();
}

您正在捕获任何异常并将消息作为String返回。因此,方法scanDataAndCalculateAverage的调用通常会完成"和#34;代码检查器"将Average =写在返回的String前面,因为它认为您的程序返回了有效值。

您需要将Exception传播给调用方法,以便它知道出错了。

由于它似乎是一项任务,应该尝试解决这个问题。如果您对此有疑问,请发表评论。

顺便说一句,请更改以下异常消息:

  1. "Error: " + myName + " (The system cannot find the file specified)"应为"Error: " + myName + " (No such file or directory)"
  2. myName + " does not have numerical data"应为myName + "does not have numeric data"
  3. 如果您使用邮件,则支票无法通过。奇怪的是,第一个被赋值提到了,但它使用了另一个来进行检查。

    这是整个支票的预期输出:

    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