无法从while循环退出

时间:2018-07-31 21:39:37

标签: java arrays elements

Integer[][] a = new Integer[3][3];
int value1=1;

while(a !=null) {   
    System.out.println("Please enter the value of indexes");
    i=input.nextInt();
    j=input.nextInt();

    int value= input.nextInt();
    if(!(i<0||i>2 && j<0 || j>2)) {
        if(a[i][j]== null) {
            a[i][j]=value;
            System.out.printf("value of a[%d][%d] =%d",i,j,a[i][j]);
        }
        else {
            System.out.println("Index already has value");
        }
    }
    else {
        for(i=0;i<3;i++) {
            for(j=0;j<3;j++) {
                System.out.println(a[i][j]);
            }
        }
    }

当循环的所有元素都获得值但无法正常工作时,我想退出循环,而

1 个答案:

答案 0 :(得分:1)

除非您明确设置a != null,否则

Integer[][] a = new Integer[3][3];在语句a = null之后的所有点上都为true。 a != null不检查数组内容。它只会检查数组是否存在。

如果要在a的所有条目都不为空时停止循环,则可以改用while (Arrays.asList(myArray).contains(null))。这将在每次while循环迭代开始时检查该数组,并在该数组不包含任何空值时停止。


为获得更有效的选择,您还可以创建一个初始化为a.length的计数器,并在每次填充数组插槽时将其递减。

Integer[][] a = new Integer[3][3];
int value1=1;
int remaining = a.length;

while (remaining > 0) {   
    System.out.println("Please enter the value of indexes");
    i=input.nextInt();
    j=input.nextInt();

    int value= input.nextInt();
    if(!(i<0||i>2 && j<0 || j>2)) {
        if(a[i][j]== null) {
            a[i][j]=value;
            remaining--;
相关问题