各位大大好~
我是剛學java的新手
在課本上練習使用命令列參數args的範例時,不知為何跑出來的結果和事實不同 QQ
程式可以跑,但是結果都不一定是正確的,有試過檢查x,y的類別,卻結果還是...
想請問是不是哪裡有遺漏掉呢? 感謝~
程式碼:
import java.lang.*;
class ch7_10
{
public static void main(String[] args)
{
if(args.length !=3)
{
System.out.println("請使用這個公式處理");
System.exit(0); //結束程式
}
int ans=0;
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[2]);
switch (args[1].charAt(0))
{
case '+': ans= x + y;
case '-': ans= x - y ;
case '*': ans=x * y;
case '/': ans= x / y;
}
System.out.printf("%s %s %s = %d%n",args[0],args[1],args[2], ans);
結果:
public static void main(String args[]) {
if(args.length !=3)
{
System.out.println("請使用這個公式處理");
System.exit(0); //結束程式
}
int ans=0;
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[2]);
switch (args[1])
{
case "+" -> ans= x + y;
case "-" -> ans= x - y;
case "*" -> ans= x * y;
case "/" -> ans= x / y;
}
System.out.printf("%s %s %s = %d%n",args[0],args[1],args[2], ans);
}
大家都說break, 提供一個有趣的答案, 限定Java 12以上
參考
或是找找Enhanced Switch Expression
break做與不做的影響是case的穿透效果
參考
可以仔細去看中間範例的
switch(quotient) {
case 10:
case 9: