好吧,我有一个带有 switch 语句的方法,但我省略了其余的情况,因为它们并不重要。在我的主要方法中,调用运算符方法并在 while 循环中传递参数“选择”,直到他们选择“Q”。
当用户输入负数时,它应该抛出异常,打印一条消息,并忽略他们的输入,然后循环回到开头。当抛出此异常时,它会终止程序。任何帮助将非常感激。谢谢!
public static void operator(String selection) throws IllegalArgumentException{
Scanner input = new Scanner(System.in);
double price;
switch(selection){
case "A":
System.out.println("Enter the price");
if(input.nextDouble()<0){
throw new IllegalArgumentException("Price cannot be a negative value");
}
else{
price = input.nextDouble();
}
break;
case"Q":
System.exit(0);
}
}
Run Code Online (Sandbox Code Playgroud)