首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法从while循环中退出

无法从while循环中退出
EN

Stack Overflow用户
提问于 2018-08-01 05:39:37
回答 1查看 32关注 0票数 0
代码语言:javascript
复制
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进行了检查,当循环的所有元素都获得一个值但它不工作时,我想离开循环

EN

回答 1

Stack Overflow用户

发布于 2018-08-01 05:46:45

除非您显式设置了a = null,否则在语句Integer[][] a = new Integer[3][3];之后的所有点上,a != null都将为真。a != null不检查有关数组内容的任何内容;它只检查数组是否存在。

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

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

代码语言:javascript
复制
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--;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51622488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档