代码如下:
public class Demo6 {
public static void main(String[] args){
System.out.println(firstNum("5x"));
System.out.println(firstNum(""));
System.out.println(firstNum("X"));
System.out.println(firstNum(null));
}
public static int firstNum(String str) {
try{
char c = str.charAt(0);
if(c<'0' || c>'9'){
throw new RuntimeException("the first if not digit");
}
return str.charAt(0) - '0';
}catch(NullPointerException e){
e.printStackTrace();
return -1;
}catch(StringIndexOutOfBoundsException e){
e.printStackTrace();
return -2;
}catch(Exception e){
e.printStackTrace();//打印方法的调用栈跟踪
return -3;
}finally{//无论是否有异常,总是被执行的代码
return -4;
}
}
}每次执行到空指针那里,就不再运了了。空指针异常
public class Demo6 {
public static void main(String[] args){
System.out.println(firstNum("5x"));
System.out.println(firstNum(""));
System.out.println(firstNum("X"));
System.out.println(firstNum(null));
}
public static int firstNum(String str) {
try{
char c = str.charAt(0);
if(c<'0' || c>'9'){
throw new RuntimeException("the first if not digit");
}
return str.charAt(0) - '0';
}catch(NullPointerException e){
e.printStackTrace();
return -1;
}catch(StringIndexOutOfBoundsException e){
e.printStackTrace();
return -2;
}catch(Exception e){
e.printStackTrace();//打印方法的调用栈跟踪
return -3;
}finally{//无论是否有异常,总是被执行的代码
return -4;
}
}
}每次执行到空指针那里,就不再运了了。空指针异常
解决方案 »
- javase程序怎样在网页上打开?
- JTextArea 实现如UltraEdit 查找功能
- for(;;)和while(true)的区别
- jsp程序,进入网页中。注册一个新用户时,报错,哪位帮忙看一下???谢谢
- 一个简单的画图问题~白送分了~
- 取得JCheckBox选中的个数
- 想了好久也不知道怎么错的,向高手求助!
- 怎样在一个public class MyClass{} 这样的java类中得到当前运行的tomcat中的虚拟目录的觉对路径?
- javascript 中的document.all哪位给解释一下,谢谢?
- JNDI的具体用法???
- 检验大家的finally学的程度的一段代码,你能全部答对吗?
- java面试题,纠结了半天只做了一半,在线等高手解答!
你可以这样改应该就是你要的结果了
int result=-4;
try{
char c = str.charAt(0);
if(c<'0' || c>'9'){
throw new RuntimeException("the first if not digit");
}
return str.charAt(0) - '0';
}catch(NullPointerException e){
e.printStackTrace();
result = -1;
}catch(StringIndexOutOfBoundsException e){
e.printStackTrace();
result = -2;
}catch(Exception e){
e.printStackTrace();//打印方法的调用栈跟踪
result = -3;
}finally{//无论是否有异常,总是被执行的代码
return result;
}
下面是结果:
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:687)
at Demo6.firstNum(Demo6.java:12)
at Demo6.main(Demo6.java:4)
java.lang.RuntimeException: the first if not digit
at Demo6.firstNum(Demo6.java:14)
at Demo6.main(Demo6.java:5)
java.lang.NullPointerException
at Demo6.firstNum(Demo6.java:12)
at Demo6.main(Demo6.java:6)
-4
-4
-4
-4
这位仁兄LZ的代码测试意图应该是没错的。
因为finally中的内容会抢在return之前运行。而finally中恰好有个return
由于finally中抢先return了,这样相当于try catch中的return都无效了。
这位仁兄LZ的代码测试意图应该是没错的。
因为finally中的内容会抢在return之前运行。而finally中恰好有个return
由于finally中抢先return了,这样相当于try catch中的return都无效了。嗯,有道理
这个地方的str就不能调用其中的函数了。
因为charAt()这个函数是类中飞静态函数,它只能用类的实例来调用。哪怕你上面写的str=“”它也是有实例的所以可以用,而str=null时没有实例就不能调用了