gaurav.ncst
gaurav.ncst

Reputation: 19

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();    
        }
    }

}

Upvotes: 1

Views: 1670

Answers (5)

Jens
Jens

Reputation: 69495

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

Upvotes: 7

RVarttinen
RVarttinen

Reputation: 89

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?

Upvotes: 0

piaomiaohan
piaomiaohan

Reputation: 1

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

Upvotes: -1

Hirak
Hirak

Reputation: 3649

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();
      }
  }

Upvotes: 0

chresse
chresse

Reputation: 5817

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++)

Upvotes: 0

Related Questions