troopers97
troopers97

Reputation: 91

For loop in Java for filling up table

Let's say i have a table format in Java

  0    1    2
|_E_|____|____| 0
|___|____|____| 1

Where the numbers at the top are the index of the column and the numbers on the side are the index of the row. A function:

add_at(x,y)

takes two arguments x and y which is the x coordinate and y coordinate. I'm trying to fill up the table using a for loop for which it begins from the position 0,1 which is

  0    1    2
|_E_|__x_|____| 0
|___|____|____| 1

marked with x, followed by 0,2

  0    1    2
|_E_|__x_|__x_| 0
|___|____|____| 1

proceeding with

  0    1    2
|_E_|__x_|__x_| 0
|_x_|____|____| 1

  0    1    2
|_E_|__x_|__x_| 0
|_x_|__x_|____| 1

  0    1    2
|_E_|__x_|__x_| 0
|_x_|__x_|__x_| 1

until the table is filled except for the location 0,0 which is marked by E.

int max_row = 1;    //maximum row length is 1
int max_col = 2;    //maximum column length is 2

for (int x = 0; x<=max_row; x++) {
    for (int y = 1; y<max_col; y++) {
        this.add_at(x,y)
        }
    }

I'm a beginner at Java and I'm pretty sure the for loop i wrote is wrong in a way where i wanted the output to be. Would appreciate some help on this.

Upvotes: 1

Views: 1050

Answers (2)

Doston
Doston

Reputation: 637

You can do as following, and u can change the code according to your needs:

    public class Table {
    public static void main(String[] args) {
      int maxRow = 4;    //maximum row length is 4
      int maxCol = 5;    //maximum column length is 5

      for (int x = 0; x<maxRow; x++) {
        for (int y = 0; y<maxCol; y++) {
          if (x==0 && y==0){
            System.out.print("| |");
            continue;
          }
          add_at(x, y);
        }
        System.out.println();
      }
    }

    public static void add_at(int x, int y) {


      System.out.print("|x|");
    }
  }

The result will be like:

| ||x||x||x||x|
|x||x||x||x||x|
|x||x||x||x||x|
|x||x||x||x||x|

You can see the screenshot from the output: enter image description here

I hope the code helps you

Upvotes: 0

Michael
Michael

Reputation: 44170

Change y to be initialised to zero (i.e. populate all rows) and add a special condition for (0,0).

Also, both conditions should use <=.

int max_row = 1;    //maximum row length is 1
int max_col = 2;    //maximum column length is 2

for (int x = 0; x <= max_row; x++) {
    for (int y = 0; y <= max_col; y++) {
        if (x == 0 && y == 0) continue;
        this.add_at(x,y);
    }
}

Upvotes: 3

Related Questions