在我的print()方法中调用getCurrent()方法时,我很难将错误消息打印到控制台。另外,在我的getCurrent()方法中,编译器说我需要返回一个double。我不了解返回双精度问题,不应将try catch块换成对getCurrent()的调用。

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


您捕获了自己的throws 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/

10-10 10:48