简体   繁体   English

NumberFormatException乘法时

[英]NumberFormatException while multiplying

I'm trying to 'Run Configurations' in Eclipse. 我正在尝试在Eclipse中“运行配置”。 When I pass something like '1 + 2', or '123 - 321', or '123 / 321' it works well. 当我通过“ 1 + 2”或“ 123-321”或“ 123/321”之类的东西时,它会很好地工作。 The problem appears when I try to do multiplying. 当我尝试进行乘法运算时会出现问题。 In this case I get 在这种情况下

Exception in thread "main" java.lang.NumberFormatException: For input string: ".project"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Main.main(Main.java:15)

Here's the code: 这是代码:

public class Main {

public static void main(String[] args) {
    double aNum;
    double bNum;
    char operator;
    String result = "Error";
    Calculator calc = new Calculator();

    if (args.length == 0) {
        System.out.println("No parameters were entered");
    }
    else {
        aNum = Double.parseDouble(args[0]);
        bNum = Double.parseDouble(args[2]);
        operator = args[1].charAt(0);
        result = calc.calculate(aNum, bNum, operator);

        System.out.println(result);
    }
}

}


public class Calculator {
public String calculate(double aNum, double bNum, double operator) {
    String result = "Error";
    if(operator=='+'){
        result = String.valueOf(aNum+bNum);
    }
    else if (operator=='-') {
        result = String.valueOf(aNum-bNum);
    }
    else if (operator=='*') {
        result = String.valueOf(aNum*bNum);
    }
    else if (operator=='/') {
        if (bNum==0) {
            System.out.println("Forbidden operation: div by zero!");
        }
        else {
            result = String.valueOf(aNum/bNum);
        }
    }
    else {
        System.out.println("Unhandled operator. Please use '+-*/' as operators");
        result = "Error";
    }
    return result;
}
}

The problem is how you're invoking the program. 问题是您如何调用该程序。 If you run: 如果您运行:

java Calculator 5 * 10

then in some command shells, the * will be automatically expanded to all filenames in the current directory. 然后在某些命令解释程序中, *将自动扩展为当前目录中的所有文件名。 You should be able to fix this with quoting, eg 您应该能够通过引用解决此问题,例如

java Calculator 5 '*' 10

Or ask for the values from within the calculator, instead of taking them from the command line. 或从计算器中索取值,而不是从命令行获取它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM