日期:2014-05-20  浏览次数:20775 次

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 ;在更高一级的作用域,这个要被初始化。 

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