public class Calculator {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java Calculator operand1 operator operand2");
System.exit(0);
}
int result = 0;
switch (args[1].charAt(0)) {
case '+':
result = Integer.parseInt(args[0]) + Integer.parseInt(args[1]);
break;
case '-':
result = Integer.parseInt(args[0]) - Integer.parseInt(args[1]);
break;
case '*':
result = Integer.parseInt(args[0]) * Integer.parseInt(args[1]);
break;
case '/':
result = Integer.parseInt(args[0]) / Integer.parseInt(args[1]);
break;
}
System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
}
}
当我在终端中运行Calculator.java
时,我尝试了以下几种方法:
Rasperry:src maggiesmac$ javac Calculator.java
Rasperry:src maggiesmac$ java Calculator 1+2
Usage: java Calculator operand1 operator operand2
Rasperry:src maggiesmac$ java Calculator 1 + 2
Exception in thread "main" java.lang.NumberFormatException: For input string: "+"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:572)
at java.lang.Integer.parseInt(Integer.java:615)
at Calculator.main(Calculator.java:15)
Rasperry:src maggiesmac$ java Calculator.main(1,+,2)
-bash: syntax error near unexpected token `('
那么如何调用 Java main()
方法呢?我应该如何将参数传递给它?
请更改案例结构中的索引(如 @SotiriosDelimanolis 所示(。此外,我们可以在以下情况下使用字符串:
public class Calculator {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java Calculator operand1 operator operand2");
System.exit(0);
}
int result = 0;
switch (args[1]) {
case "+":
result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
break;
case "-":
result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
break;
case "*":
result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
break;
case "/":
result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
break;
}
System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
}
}
你也可以试试下面的代码得到结果
class Calculator {
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: java Calculator operand1 operator operand2");
System.exit(0);
}
int result = 0;
char op = args[1].charAt(0);
System.out.println((int)op);
int ope = (int)op;
switch (ope) {
case 43:
result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
break;
case 45:
result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
break;
case 42:
result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
break;
case 47:
result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
break;
}
System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
}
}