我不确定如何为计算器创建命令行参数,有帮助吗?到目前为止,这是我的代码。我被要求做的问题在代码的块注释中。
import java.util.Scanner;
public class M93 {
public static void main(String[] args) {
/* A simple calculator program is expecting command line arguments that have the form <operand1> <operator> <operand> where both <operand1> and <operand2>
are integers while <operator> is one of +, -, *, /, or %. Write a method that will calculate and return the value of <operand1> <operator> <operand2>.
For example, if the command line arguments are 5 + 3, the method should return the value 8. Assume that the command line argument values are all valid.
*/
String s = new String[5];
operator[0] = "+";
operator[1] = "-";
operator[2] = "*";
operator[3] = "/";
operator[4] = "%";
String inputOperator;
int a, b;
Scanner scanner = new Scanner(System.in);
System.out.println("Calculator: " + scanner.nextInt() );
}
public static int addition(int a, int b, int answer) {
answer = (a + b);
System.out.println(answer);
return answer;
}
}
最佳答案
您不必使用Scanner
。
像这样运行程序:
java ClassName 2 3 +
public static void main(String[] args) {
int frstOperand = Integer.parseInt(args[0]);
int secndOperand = Integer.parseInt(args[1]);
String operator = args[2];
System.out.println("Result :" + doOpearation(frstOperand,secndOperand,operator));
}
static int doOpearation(int i,int j, String op) {
switch (op) {
case "+":
return i+j;
case "-":
return i-j;
case "*":
return i*j;
case "/":
return i/j;
default:
System.out.println("Please enter a valid opearator");
return 0;
}
}