【发布时间】:2016-02-02 10:11:49
【问题描述】:
这个问题是微不足道的,但我在这里遗漏了一些非常基本的东西并且无法抓住它。请帮忙。 我正在编写一个简单的计算器程序以在命令行中使用。源代码如下。 问题是当我使用计算器时
>java SwitchCalc 12 * 5
它在从 args[2] 解析第二个 int 的语句中为输入字符串“002.java”抛出一个“java.lang.NumberFormatException”:
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);
}
}
【问题讨论】:
-
您能在执行任何操作之前尝试打印所有参数吗?
-
这与 Java 无关——它是你的 shell 进行通配符扩展。我猜您在运行此代码的目录中有两个或多个文件,其中一个名为
002.java。 -
我刚才尝试的是下面的代码:'for(int i = 0; i ALL 个 ffile。顺便说一句,我使用的是 Windows 10 的 cmd shell。
-
@AndyTurner 我想这是正确的。
标签: java string input command-line-arguments numberformatexception