【问题标题】:Unable to exit from while loop无法退出while循环
【发布时间】:2018-07-31 21:39:36
【问题描述】:
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]);
            }
        }
    }

当我想在循环的所有元素都获得一个值但它不工作时离开循环时,我已经对 in 进行了检查

【问题讨论】:

    标签: java arrays elements


    【解决方案1】:

    a != null 在声明 Integer[][] a = new Integer[3][3]; 之后的所有点都为真,除非您明确设置 a = nulla != 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--;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      相关资源
      最近更新 更多