命令行参数在Java中不处理“ *”

问题描述 投票:0回答:1

我正在编写程序以对命令行参数的值进行加,乘或除运算。

args将以波兰语符号传递,例如+ 3 2* 2.0 5.1

如果参数的长度不为3,或args[0]不等于+*/,则将显示错误消息。

String operation = args[0];

if (args.length != 3 || !(operation.equals("+") && operation.equals("*") && operation.equals("/")))
  System.out.println("oops");

else {
  switch(operation)
              {
                case "+": {
                  first = Double.parseDouble(args[1]);
                  second = Double.parseDouble(args[2]);
                  sum = first + second;
                  System.out.println(sum);
                  break;
                }

                case "*": {
                  first = Double.parseDouble(args[1]);
                  second = Double.parseDouble(args[2]);
                  product = a * b;
                  System.out.println(product);
                  break;
                }

                case "/": {
                  first = Double.parseDouble(args[1]);
                  second = Double.parseDouble(args[2]);
                  quotient = a / b;
                  System.out.println(quotient);
                  break;
                }
              }
}

它既适用于+也适用于/,但是当我输入*时,程序将显示oops。我将*更改为“ x”,然后它可以正常工作。作为命令行arg传递的字符串“ *”出了点问题。

java switch-statement command-line-arguments
1个回答
0
投票

您正在检查错误的条件,而不是声明变量:

String operation = args[0];
if (args.length != 3 || (!operation.equals("+") && !operation.equals("*") && !operation.equals("/")))
    System.out.println("oops");
else {
    double first = Double.parseDouble(args[1]), second = Double.parseDouble(args[2]), sum, product, quotient;
    switch(operation){
        case "+": {
            sum = first + second;
            System.out.println(sum);
            break;
        }
        case "*": {
            product = first * second;
            System.out.println(product);
            break;
        }
        case "/": {
            quotient = first / second;
            System.out.println(quotient);
            break;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.