我可以在switch case語句中使用用戶輸入語句嗎?我可以在switch case語句中使用用戶輸入語句嗎?
這是我的代碼。
switch(choice) {
System.out.println("Enter First Number");
num1=input.nextInt();
System.out.println("Enter Second Number");
num2=input.nextInt();
case 1:
total=num1+num2;
System.out.println("Addition of "+num1+" and "+num2+" are "+total);
break;
case 2:
total=num1-num2;
System.out.println("Substraction of "+num1+" and "+num2+" are "+total);
break;
case 3:
total=num1*num2;
System.out.println("Multiplication of "+num1+" and "+num2+" are "+total);
break;
case 4:
total=num1/num2;
System.out.println("Divistion of "+num1+" and "+num2+" are "+total);
break;
default:
System.out.println("Please Choose right option...Try again");
break;
}
這在Java中可能嗎?
你爲什麼要這麼做?爲什麼不簡單地在switch語句之前獲取輸入,然後在輸入無效的情況下在do-while循環內再次獲取輸入? –
這是不可能的在switch case語句中? – Mathur
如果編譯器說你不能做某件事,那麼答案就是你無法做到。 – dasblinkenlight