62,616
社区成员
发帖
与我相关
我的任务
分享
//利用命令行参数 做计算器
public class TestCal
{
public static void main(String[] args)
{
if(args.length < 3)
{
System.out.println("input parameter number is under 3");
System.exit(-1);
}
double d1=0,d2=0;
try
{
d1 = Double.parseDouble(args[0]); //parseDouble是一个static函数,故直接用类名就可以调用
d2 = Double.parseDouble(args[2]);
}catch(NumberFormatException NE)
{
System.out.println("input parameter include string!");
NE.printStackTrace();
System.exit(-1);
}
double Result = 0;
try
{
if(args[1].equals("+"))
Result = d1 + d2;
else if(args[1].equals("-"))
Result = d1 - d2;
else if(args[1].equals("×"))
Result = d1 * d2;
else if(args[1].equals("/")) //此种情况下,d2为0 下面的catch却不执行 捕获不到 ?????
Result = d1 / d2;
else
{
System.out.println("the secaond paramter shoulde be operator");
System.exit(-1);
}
}catch(ArithmeticException AE) //除数为0捕获
{
System.out.println("divisor is 0!");
AE.printStackTrace();
System.exit(-1);
}
System.out.println(args[0]+args[1]+args[2]+ " = " + Result);
}
}
try { double i = 10; System.out.println(1/0); } catch (ArithmeticException e){ System.out.println("除数不能为0"); } 不是说double c除以0 不会报异常吗 为何我上面的代码确能捕获异常
12
那这个怎么办呢?算是语言的漏洞或者不规范
把ArithmeticException换成RuntimeException试试
或者干脆用Exception
try { double i = 10; System.out.println(1/0); } catch (ArithmeticException e){ System.out.println("除数不能为0"); } 不是说double c除以0 不会报异常吗 为何我上面的代码确能捕获异常
System.out.println(1.0 / 0);//打印"Infinity"
System.out.println(-1.0 / 0);//打印"-Infinity"
System.out.println(0.0 / 0.0);//打印"NaN"
Infinity是无穷大的意思。
这个是java算术的一个机制。