Louie Morris
Louie Morris

Reputation: 55

Making a block of X's with a number

I am trying to have the user enter a number and have the computer output a square with side of that number.

For example:

Enter a number:
4

XXXX
XXXX
XXXX
XXXX

I got this far, but don't know what else to do:

package blockmaker;
import java.util.*;

public class BlockMaker {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int number = scan.nextInt();
        scan.nextLine();

        for(int i = 0; i < number; i++){
            System.out.println("X");
        }
    }

}

My current code outputs:

Enter a number: 
4
X
X
X
X

Do I need to put a loop inside a loop?

Upvotes: 2

Views: 243

Answers (2)

Mitesh Pathak
Mitesh Pathak

Reputation: 1211

for(int i = 0; i < number; i++){
            System.out.println("X"); // print X and new line
}

Above code prints "X" in each line. Instead you need to print "X" number(n) times in each line. You need a nested loop.

for(int i = 0; i < number; i++){
    for(int j = 0; j < number; j++)
        System.out.print("X"); // print X - n times
    System.out.println(); // print new line
}

Upvotes: 1

M A
M A

Reputation: 72884

Yes you need an inner loop for that:

for(int i = 0; i < number; i++){
    for(int j = 0; j < number; j++) {
        System.out.print("X");
    }
    System.out.println();
}

Upvotes: 1

Related Questions