谁能给我解释一下为什么add()方法返回0而不是4?我正在尝试使用int 0,以防提供“无效”的字符串号(例如4)。我得到了字符串参数3,4 / 3,4 /3,4/4,4/的正确结果,但不是3,4。
你能给我一些提示吗?我哪里做错了?谢谢!
public class Numbers2
{
public static void main(String[] args) {
System.out.println(add("d","4"));
} // main() method
public static int add(String a, String b)
{
int x = 0;
int y = 0;
try{
x = Integer.parseInt(a);
y = Integer.parseInt(b);
System.out.println("No exception: " + (x+y));
return x + y;
}
catch (NumberFormatException e){
if(x != (int) x ){
x = 0;
}
if(y != (int) x ){
y = 0;
}
return x + y;
}
} // add() method
} // class
发布于 2013-01-27 11:53:15
问题是y = Integer.parseInt(b);行没有机会执行,因为您将"d"作为第一个不是整数的参数传递,x = Integer.parseInt(a);行导致异常,并且x和y都保持为0。
您可以通过对这两者分别使用try/catch来解决这个问题:
int x = 0; //x is 0 by default
int y = 0; //y is 0 by default
try {
x = Integer.parseInt(a); //x will remain 0 in case of exception
}
catch (NumberFormatException e) {
e.printStackTrace();
}
try {
y = Integer.parseInt(b); //y will remain 0 in case of exception
}
catch(NumberFormatException e) {
e.printStackTrace();
}
return x + y; //return the sum发布于 2013-01-27 11:48:38
因为第二个参数是"d",所以总是会出现异常情况。这里,x=y= 0。
这里的If语句不会做任何事情,因为当x是整数时,(x == ( int )x)总是这样,并且(y == (int)x)因为它们都是0,所以这两个块都不会被执行。
因此,x+y总是= 0。
发布于 2013-01-27 12:04:26
如果将错误的formate参数用作第一个参数,则会在语句中发生异常
x = Integer.parseInt(a);这条线
y = Integer.parseInt(a);在这种情况下永远不会执行,所以对每条语句使用不同的try-catch块。
https://stackoverflow.com/questions/14544203
复制相似问题