【问题标题】:Using * in command line in a Java program在 Java 程序的命令行中使用 *
【发布时间】: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


【解决方案1】:

* 是一个通配符,对 shell 有特殊意义。它甚至在传递给程序之前就被展开了。

在您的情况下,星号已替换为目录中所有文件的名称,其中第一个似乎是002.java。尝试将此字符串解析为 Integer 会导致给定异常。

通过将其包裹在"*" 引号中,它被shell 视为文字并简单地按原样传递给程序。根据您使用的 shell,您还应该能够使用 \* 反斜杠转义星号。

另请参阅Wikipedia article about glob patterns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2011-01-16
    • 2019-05-30
    • 2015-06-15
    相关资源
    最近更新 更多