这个问题很简单,但我在这里遗漏了一些非常基本的东西并且无法捕捉到它。请帮忙。 我正在编写一个简单的计算器程序以在命令行中使用。源代码如下。 问题是当我使用计算器时
>java SwitchCalc 12 * 5
它在从 args[2] 解析第二个 int 的语句中为输入字符串抛出“java.lang.NumberFormatException”:“002.java”:
int value2 = Integer.parseInt(args[2])
后来我尝试了以下方法,它起作用了。
>java SwitchCalc 12 "*" 5
12 * 5 = 60
我错过了什么?
/*
User will input the expression from command-line in the form:
>java SwitchCalc value1 op value2
where,
value1, and value2 are integer values
op is an operator in +, -, *, /, %
Program will evaluate the expression and will print the result. For eg.
>java SwitchCalc 13 % 5
3
*/
class SwitchCalc{
public static void main(String [] args){
int value1 = Integer.parseInt(args[0]),
value2 = Integer.parseInt(args[2]),
result = 0;
switch(args[1]){
case "+":
result = value1 + value2;
break;
case "-":
result = value1 - value2;
break;
case "*":
result = value1 * value2;
break;
case "/":
result = value1 / value2;
break;
case "%":
result = value1 % value2;
break;
default:
System.out.printf("ERROR: Illegal operator %s.", args[1]);
break;
}
System.out.printf("%d %s %d = %d", value1, args[1], value2, result);
//System.out.println(value1 + " " + args[1] + " " + value2 + " = " + result);
}
}
最佳答案
*
是一个对 shell 有特殊意义的通配符。它甚至在传递给程序之前就已展开。
在您的例子中,星号已替换为目录中所有文件的名称,其中第一个似乎是 002.java
。尝试将此字符串解析为整数会导致给定异常。
通过将其包裹在 "*"
引号中,shell 会将其视为文字,并按原样简单地传递给程序。根据您使用的 shell,您还应该能够使用 \*
反斜杠转义星号。
关于java - 在 Java 程序的命令行中使用 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143748/