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;
}
}
}
请问为什么会说没有初始化呢?

解决方案 »

  1.   

    int num; 
    boolean[] arr
    是局部变量,要初始化
      

  2.   

    arr的赋值在try块里了
    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块中使用的变量,应该在块外被显式赋值
      

  3.   

    楼主是不是在运行时没有传入参数?
    例:java Test1 sdf 
    sdf就是给main()方法传入的参数。
      

  4.   

    .......
    同意楼上的看法..
    不过....
    boolean[] arr = null;
    这句持行应该会出错吧?
    BOOLEAN应该只有TURE和FALSE两个值....
    应该不能为空吧?
      

  5.   

    初始化在try里面,不一定执行。如果有异常就等于没有执行初始化。
    最后肯定会报错。
      

  6.   

    运行仍有问题。
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Test.main(Test.java:7)
      

  7.   

    你传入参数了??
    命令行 java test 1ec
    运行参数里 随便写个数字
      

  8.   


    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; 
    } args[0]是程序接受的参数
    命令行执行格式如下:
    java Test1 9
      

  9.   

    Java编译器的检查比较严格.当它在可预见的分支中没有发现被初始化的时候,那么它就会编译不通过.
    举个例子. 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); 

    这样编译也是不通过的.因为他不知道if(a)这个分支是不是能够被运行.
    但是这样是可以的 if(true){
    arr = new boolean[num];
    }
    for(int i = 0; i < arr.length; i++) { 
    arr[i] = true; 
    }因为true是固定的.它是可预见的.
    为了避免这些繁琐的规则,我们可以
    定义的时候先赋值为Null
    boolean[] arr = null; 
    这样一切都Ok了.世界安静啦!
      

  10.   

    看作用域啊,arr是在try这个花括号里面的。arr[i]同样在
    for这个花括号里面。这两个东西的作用域级别是相同的。
    boolean[] arr ;在更高一级的作用域,这个要被初始化。 
      

  11.   

    这样就行了:
    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;