简体   繁体   English

为什么此代码不打印应有的内容?

[英]Why this code does not print what it should?

This code should draw table, but it doesn't. 该代码应绘制表格,但不是。 Why? 为什么? The code compiles but it doesn't print enything. 代码可以编译,但是不会打印出任何东西。 Here is code: 这是代码:

 import java.util.Arrays;

    public class Nizovi{

    public static char table[][]= new char[10][10] ;



    public static void drawTable(){
        // this should draw table   

        int k=1;
        while(k <= 30){
            System.out.print("-");
        }
        System.out.println();

        for(int i=0; i < table.length; i++){

            for(int j=0; j < table[i].length; j++){
                System.out.print("|"+ table[i][j] + "|");
            }

            System.out.println();

        }

        k=1;
        while(k <= 30){
            System.out.print("-");
        }

    }


    public static void buildTable(){
        // and this is supposed to fill it with *    
        for(char[] row: table){
            Arrays.fill(row, '*');
        }
    }

    public static void main (String[] args){

        Nizovi.buildTable();
        Nizovi.drawTable();

    }
    }

I can't see what i miss. 我看不到我想念的东西。 What's wrong here? 怎么了

Your loop says while(k <= 30)... - how is k ever to reach 30? 您的循环显示while(k <= 30)... k如何达到30? Nothing is changing it. 什么都没有改变。

Increment k inside the while blocks: 在while块内增加k

 while(k <= 30){
        System.out.print("-");
        k++; // add this to your loops
 }

In your code, k is not updated within the loops, it therefore remains 1 and stays always less-or-equal to 30 ( k <= 30 always yields true ) 在您的代码中, k不会在循环内更新,因此它保持为1并始终小于或等于30k <= 30总是产生true

know as "an endless loop" 被称为“无尽循环”

Output with incrementing the k references within the while -blocks: 输出在while -blocks中增加k引用:

------------------------------
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
|*||*||*||*||*||*||*||*||*||*|
------------------------------

(Make sure you update both while -blocks (hence the plural)) (确保while更新两个-blocks(因此复数))

The while loop is different from for loop. while循环与for循环不同。 for assumes you are going to do something a certain amount of times and can therefore automatically increment the index by executing the i++ part. for假设您将执行某些操作,因此可以通过执行i++部分来自动增加索引。 while only checks if the condition is fulfilled. 而仅检查条件是否满足。 Therefore you should take care of the state of the condition and increment the counter k in the body of the while loop by yourself. 因此,您应该注意条件的状态,并自己增加while循环主体中的计数器k

increment k in while loop 在while循环中递增k

while(k <= 30){
    System.out.print("-");
    k++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM