读书人

try catch 有关问题

发布时间: 2011-12-23 23:32:01 作者: rapoo

try catch 问题
[code=Java][/code]public class Test1 {
public static void main(String[] args) {
int num;
boolean[] arr ;
try{
num = Integer.parseInt(args[0]);
arr = new boolean[num];
}catch(NumberFormatException e) {
System.out.println("not number");
//System.exit(-1);
}

for(int i = 0; i< arr.length; i++) {
arr[i] = true;
}
}
}
请问为什么会说没有初始化呢?

[解决办法]
args[0] 什么意思
[解决办法]
int num;
boolean[] arr
是局部变量,要初始化

[解决办法]
arr的赋值在try块里了

Java code
public static void main(String[] args) { int num = 0; boolean[] arr = null; try{ num = Integer.parseInt(args[0]); arr = new boolean[num]; }catch(NumberFormatException e) { System.out.println("not number"); //System.exit(-1); } for(int i = 0; i < arr.length; i++) { arr[i] = true; } } }
[解决办法]
楼主是不是在运行时没有传入参数?
例:java Test1 sdf
sdf就是给main()方法传入的参数。
[解决办法]
.......
同意楼上的看法..
不过....
Java code
boolean[] arr = null;
[解决办法]
初始化在try里面,不一定执行。如果有异常就等于没有执行初始化。
最后肯定会报错。
[解决办法]
没有初始化 你就给你的变量 附个初始值呗
[解决办法]
探讨
arr的赋值在try块里了


Java code
public static void main(String[] args) {
int num = 0;
boolean[] arr = null;
try{
num = Integer.parseInt(args[0]);
arr = new boolean[num];
}catch(NumberFormatException e) {
System.out.println("not number");
//System.exit(-1);
}

for(int i = 0; i < arr.length; i++) {
arr[i] = true;
}
}
}




需要在try块中使用的变量,应该在块外…

[解决办法]
Java code
            int num;             boolean[] arr = null;             try{             num = Integer.parseInt(args[0]);             arr = new boolean[num];             }catch(NumberFormatException e) {             System.out.println("not number"); //            System.exit(-1);             }             for(int i = 0; i < arr.length; i++) {             arr[i] = true;             }
[解决办法]
Java编译器的检查比较严格.当它在可预见的分支中没有发现被初始化的时候,那么它就会编译不通过.
举个例子.
Java code
        int num;         boolean[] arr ;         boolean a = true;        try{         num = Integer.parseInt(args[0]);         if(a){            arr = new boolean[num];                                }        for(int i = 0; i < arr.length; i++) {             arr[i] = true;         }        }catch(NumberFormatException e) {         System.out.println("not number");         //System.exit(-1);         }
[解决办法]
看作用域啊,arr是在try这个花括号里面的。arr[i]同样在
for这个花括号里面。这两个东西的作用域级别是相同的。
boolean[] arr ;在更高一级的作用域,这个要被初始化。

------解决方案--------------------


这样就行了:

Java code
public class Test1 { public static void main(String[] args) { int num; boolean[] arr = null; try{ num = Integer.parseInt(args[0]); arr = new boolean[num]; }catch(NumberFormatException e) { System.out.println("not number"); //System.exit(-1); } for(int i = 0; i < arr.length; i++) { arr[i] = true; } } } 

读书人网 >J2SE开发

热点推荐