简体   繁体   中英

Why does my program produce no output while it's compiling fine?

I want to create a two dimensional array. I am able to compile but not able to run

public class Arraytest1 {

    public static void main(String[] args) {
        int i, j, k = 0;
        int test[][] = new int[4][5];
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 5; j++) {
                test[i][j] = k;
                k++;
            }
        }
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 5; k++)
                System.out.print(test[i][j] + " ");

            System.out.println();    
        }
    }

}

You have an endless loop: for(j=0;j<5;k++) , you have to write for(j=0;j<5;j++)

You increment k instead of j

You have an endless loop. You are incrementing k instead of j :

for(j=0;j<5;k++)

You should change it both times to

for(j=0;j<5;j++)

Here... this should work. Just change your sub-loops making it j++ instead of k++ both top and bottom

public static void main(String[] args) {
      int i, j, k = 0;
      int test[][] = new int[4][5];
      for (i = 0; i < 4; i++) {
          for (j = 0; j < 5; j++) {
              test[i][j] = k;
              k++;
          }
      }
      for (i = 0; i < 4; i++) {
          for (j = 0; j < 5; j++)
              System.out.print(test[i][j] + " ");
          System.out.println();
      }
  }

I think you've mixed up the k and j variables in the second for-loop "block". When I alter it to:

   ... 
   for (i = 0; i < 4; i++) {
      for (j = 0; j < 5; j++)
       System.out.print(test[i][j] + " ");

      System.out.println();    
    }
    ...

I get the following printed to my console:

0 1 2 3 4 
5 6 7 8 9 
10 11 12 13 14 
15 16 17 18 19 

Is it what you wanted?

public class Arraytest1 {

    public static void main(String[] args) {
        int i, j, k = 0;
        int test[][] = new int[4][5];
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 5; j++) {
                test[i][j] = k;
                k++;
           }
        }
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 5; j++) {
                System.out.print(test[i][j] + " ");
                System.out.println();
            }
        }
    }

}

you can resolve this problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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