iT邦幫忙

0

【java】命令列參數args應用- 小型計算機

2022-05-31 16:59:52920 瀏覽
  • 分享至 

  • xImage

各位大大好~
我是剛學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);

結果:https://ithelp.ithome.com.tw/upload/images/20220531/20132078xlyDgRuePg.jpg

你知道 switch case 要加 break 嗎
iT邦新手 5 級 ‧ 2022-06-01 09:38:11 檢舉
已有補上了~ 感謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
海綿寶寶
iT邦大神 1 級 ‧ 2022-05-31 17:13:40
最佳解答

你的 switch 漏掉 break
以致於不管是 +-*/
答案都是 x/y
而由於 ans 宣告為 int (整數)
所以答案只有整數部份(例:9/8=1.125只有 1)

iT邦新手 5 級 ‧ 2022-06-01 09:38:21 檢舉

已有補上了~ 感謝

0
喵凹咿唉思嗯
iT邦研究生 5 級 ‧ 2022-06-01 00:29:27
    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: 
iT邦新手 5 級 ‧ 2022-06-01 09:38:47 檢舉

謝謝你的補充 :)

0
大圈仔来啦!
iT邦新手 5 級 ‧ 2022-06-04 16:45:49

别学JAVA了,已经烂大街,快去学前端或者go语言或者咨询安全,如果是初学编程,直接上python

我要發表回答

立即登入回答