Java 需要帮助查找平均值并打印出错误吗
我需要帮助解决这个学校的问题。如果您感兴趣,这里有一个链接: 当我试图解决这个问题时,我打印出了正确的消息,但出现了一个问题。我怀疑Codecheck的驱动程序中类似于System.out.println(“Average=“+message”);,或者类似的。所以,我最终得到的结果是 Average=squeak.txt没有数字数据 这不是我想要的。如果司机给我这个问题,我该如何解决?以下是我目前拥有的:Java 需要帮助查找平均值并打印出错误吗,java,exception-handling,Java,Exception Handling,我需要帮助解决这个学校的问题。如果您感兴趣,这里有一个链接: 当我试图解决这个问题时,我打印出了正确的消息,但出现了一个问题。我怀疑Codecheck的驱动程序中类似于System.out.println(“Average=“+message”);,或者类似的。所以,我最终得到的结果是 Average=squeak.txt没有数字数据 这不是我想要的。如果司机给我这个问题,我该如何解决?以下是我目前拥有的: import java.io.*; import java.util.*; publ
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();
}
}
}
编辑:我的新构造函数:
公共平均值(字符串名称)引发异常{
myName = name;
try{
in = new Scanner(new File(name));
}
catch (Exception e){
throw new Exception("Error: " + myName + " (No such file or directory)");
}
}
输入文件似乎包含无效的长字符。请确保有以下行:
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() + ")");
代码的问题在于这一部分:
catch (Exception e) {
return e.getMessage();
}
您正在捕获任何异常并将消息作为字符串返回。因此,方法scandaandcalculateaverage
的调用“正常”完成,“代码检查器”将Average=
写入返回的字符串前面,因为它认为您的程序返回了有效值
您需要将异常传播到调用方法,以便它知道发生了错误
既然这似乎是一项任务,你应该设法解决它。如果你对此有疑问,请留下评论
顺便说一句,请更改以下异常消息:
“错误:”+myName+“(系统找不到指定的文件)”
应该是“错误:”+myName+“(没有这样的文件或目录)”
myName+“没有数字数据”
应该是myName+“没有数字数据”
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
或者您正在抛出一个异常,该异常由驱动程序中的某个错误处理代码打印。因为您的异常消息中有确切的文本。您好。我传播了我的ScandaAndCalculateAverage()方法并解决了该问题,但我现在遇到了构造函数的问题。每当程序尝试使用不存在或不在该位置的文件运行时,我都会遇到以下错误:未报告的异常异常;必须捕获或声明为抛出+avg4.scandaandcalculateAverage())你知道我应该如何解决这个问题,因为传播它不起作用(或者可能是我做的那部分错了?)?因为你使用了一个,你必须处理它们。要么在方法头上添加一个
throws
子句,要么使用try/catch
块。第一个不起作用,因为“checker”不要期望:P。第二种可能性在这里对我们也没有帮助。因此您需要使用未检查的异常
。例如抛出新的RuntimeException(“…”)
。如果这是新的内容,那么您可能需要找到另一种方法。我仍然有这个问题。我可能不理解这里的内容,因为我不太理解这些术语。我将编辑帖子,向您展示我的新构造函数。@Yazeth您为什么要更改构造函数?您的问题在ScandaandCalculateAverage
m中ethod,而不是构造函数中的。你不必更改“他”。哦,我只是怀疑,因为每当它尝试使用不存在的文件时都会失败,所以我只是猜测构造函数有问题。