Reputation: 55
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
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
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