所以我最近了解到的異常處理Java和我還在努力去習慣它和所有,但我覺得我失去了一些東西。我爲我的課做了一個任務,編譯器不喜歡我的代碼。Java的異常處理分配
我應該做一個計算器,它需要一個運算符,然後是一個數字,如果給定的運算符(+, - ,*,/)不是前面提到的四個運算符之一,那麼拋出異常。
我用的try-catch,但由於某些原因,try和catch不認識對方,除非我把它們彼此相鄰這是不是我真正想要的東西。
我的問題是真的:有沒有我的try和catch相互承認而不旁邊對方的方式,這樣我就可以在兩者之間它們運行的代碼?或者這是不可能的,我做的全部都是錯的?
這裏是我到目前爲止的代碼:
import java.util.*;
public class Calculator
{
public static void main(String[] args)
{
String operatorInput;
double numberInput;
String userRedo = "Y";
double result = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Type in an arithmetic operator of your choice and press enter.");
System.out.println("Then, please type in a number that will undergo the operation.");
while((userRedo.toUpperCase()).compareTo("Y")==0)
{
try
{
operatorInput = input.nextLine();
if(operatorInput.compareTo("+")!=0||operatorInput.compareTo("-")!=0||
operatorInput.compareTo("*")!=0||operatorInput.compareTo("/")!=0)
{
throw new UnknownOperatorException("Unknown operator!");
}
}
numberInput = input.nextDouble();
if(operatorInput.compareTo("+")==0)
{
result += numberInput;
} else if(operatorInput.compareTo("-")==0)
{
result -= numberInput;
} else if(operatorInput.compareTo("*")==0)
{
result = result * numberInput;
} else
{
result = result/numberInput;
}
System.out.println("\nresult "+operatorInput+" "+numberInput+"= ");
System.out.println("Updated result: "+result);
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
catch(UnknownOperatorException e)
{
System.out.println(e.getMessage());
}
}
}
}
和這裏的異常類我做:
public class UnknownOperatorException extends Exception
{
public UnknownOperatorException()
{
super("Please select an actual operator and try again: ");
}
public UnknownOperatorException(String message)
{
super(message);
}
}
嘗試和趕上必須是彼此相鄰。如果你試圖通過讓他們分開來完成某件事,那麼可能有一種方法可以實現這個目標 – Ghost
哦,真的嗎?我想我必須改變我做事的方式。感謝您的快速回復。 – user3053612
在一種方法中,你會拋出一個異常**並捕獲*相同*異常**,這似乎很奇怪。如果是我,我會用一種方法拋出異常,並在我稱之爲第一種方法的方法中捕獲它。你確定你的任務不要求你這樣做嗎? –