遇到从命令行输入的计算器有问题 [英] Having a problem with a calculator that takes input from command line
本文介绍了遇到从命令行输入的计算器有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对此代码有疑问:
I''m having a problem with this code:
public class Calculator
{
public static void main(String[] args)
{
try
{
int result = 0;
try
{
switch (args[1].charAt(0))
{
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);
}
catch(NumberFormatException ex)
{
System.out.println(ex.getMessage());
System.exit(0);
}
}
catch(Exception ex)
{
System.out.println("You have to enter it in as: Number1 operator Number2");
System.exit(0);
}
}
}
问题是,当我在命令行中输入3 + 3时,它可以工作,但是如果我写3 * 3,则arg数组会打印出Calculator.class,为什么会发生这种情况?
The problem is that when I toss in 3 + 3 in the command line it works but if I write 3 * 3 the arg array prints out the Calculator.class, why does this happen?
Also Is there a way in NumberFormatException catch to print out the offending input?
推荐答案
问题还在于*字符由外壳程序解释,并由列表替换进行调用的目录中的文件和目录.您需要使用另一个字符来表示乘号或在(双引号)字符内提交*,这样:
The problem is that the * character is interpreted by the shell and is replaced by a list of the files and directories in the directory that the call is made from. You need to use another character to represent multiply or submit the * within " (double quote) characters thus:
java Calculator 3 "*" 3
// or using x character
java Calculator 3 x 3
如何启动调试器,设置一些断点等?
如果还没有免费的工具,请使用免费的Visual Studio Express Edition.
干杯
Uwe
How about firing up a debugger, setting some breakpoints, and the like?
Just use the free Visual Studio Express Edition, if you have no such tool yet.
Cheers
Uwe
这篇关于遇到从命令行输入的计算器有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文