Java知识点汇总-2

目录

1 变量的作用域 

2 二维数组的定义

 

1 变量的作用域 

实例代码:

public void fight(String name){
   if ("Bean".equals(name)){
     Plant plant =  new Bean();
   }else if ("Ice".equals(name)){
     Plant plant =   new Ice();
    }else {
      Plant plant =  new Wall();
    }
    plant.fight();
}

在fight方法中想根据接收到的名字创建不同的对象,最后调用方法,其中palnt是一个接口这三种对象已经实现了该接口。但在运行时下面代码是错误的因为我在if中声明了plant其作用范围只在{ }有效,因此后面直接使用是错误的。

代码修改:

  Plant plant = null;
  if ("Bean".equals(name)){
      plant =  new Bean();
  }else if ("Ice".equals(name)){
       plant =   new Ice();
   }else {
        plant =  new Wall();
   }
   plant.fight();

2 二维数组的定义

示例代码:

int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
int[][] a = new int[3][];

for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 3; j++) {
     a[i][j] = arr[i][j];
  }
}

这样会报空指针异常因为数组a的第二个维度没有被定义

int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
int[][] a = new int[3][];

for (int i = 0; i < 3; i++) {
  a[i] = new int[3];
  for (int j = 0; j < 3; j++) {
     a[i][j] = arr[i][j];
  }
}

上面的才是正确的。Java中的多维数组其本质是一维数组的数组,尽管在一开始是可以不用定义第二个维度的但在使用的还是要知道第二个维度的长度的。

原文地址:https://www.cnblogs.com/youngao/p/12016435.html