gpt4 book ai didi

java - 将异常错误消息打印到控制台

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:57 24 4
gpt4 key购买 nike

在 print() 方法中调用 getCurrent() 方法时,我很难将错误消息打印到控制台。另外,在我的 getCurrent() 方法中,编译器说我需要返回一个 double 值。我不明白 return double 问题,try catch block 不应该环绕对 getCurrent() 的调用吗?

获取当前方法:

    public double getCurrent() throws IllegalStateException{
//check if element
try{
if(isCurrent() == true){
return data[cursor];
}else{
throw new IllegalStateException
("No Element");
}//end check
}//end try
catch(IllegalStateException e){
//print error message to console
System.out.println(e.getMessage());
}//end catch
}//end method

isCurrent() 方法:

    public boolean isCurrent(){
if(cursor < manyItems){
return true;
}else{
return false;
}
}//end method

print() 方法:

    public void print(){
double answer;
System.out.println(" Capacity = " + data.length);
System.out.println(" Length = " + manyItems);
System.out.println(" Current Element = " + getCurrent());
System.out.print("Elements: ");
for(int i = 0; i < manyItems; i++){
answer = data[i];
System.out.print(answer + " ");
}//end loop
System.out.println(" ");
}//end method

主要方法(不可调整):

  DoubleArraySeq x = new DoubleArraySeq();
System.out.println("sequence x is empty");
x.print();
System.out.println("Trying to get anything from x causes an exception\n");
System.out.printf("%5.2f", x.getCurrent());

正确输出:

序列 x 为空

容量=10

长度=0

没有元素

元素:

尝试从 x 获取任何内容会导致异常

最佳答案

public double getCurrent() throws IllegalStateException{
//check if element
try{
if(isCurrent() == true){
return data[cursor];
}else{
throw new IllegalStateException("No Element");
}//end check
}//end try
catch(IllegalStateException e){
//print error message to console
System.out.println(e.getMessage());
}//end catch
}//end method

您捕获自己的抛出 IllegalStateException。删除您的 try{}catch(){}

public double getCurrent() throws IllegalStateException{
//check if element
if(isCurrent() == true){
return data[cursor];
}else{
throw new IllegalStateException("No Element");
}//end check
}//end method

主要:

try{

DoubleArraySeq x = new DoubleArraySeq();
System.out.println("sequence x is empty");
x.print();
System.out.println("Trying to get anything from x causes an exception\n");
System.out.printf("%5.2f", x.getCurrent());
}catch(IllegalStateException e){
System.err.println("This exception produce because there is no element");
}

关于java - 将异常错误消息打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40062433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com