For loop inside for loops java
Solution 1
You are using the same loop counter for both loops, i2
. So, when your inner loop executes, you are increasing the value of i2
by 1. This continues until i2
gets to your designated stop point. Then the inner loop ends. It then returns to the outer loop, and the outer loop checks if i2
is past the stop point. Since you increased the value of i2
in the inner loop, it is already past the cutoff point, and the outer loop stops.
To fix this, use separate variables for each loop. See below. I use i
for the outer loop, j
for the inner loop, and number
as the cutoff point.
public static void main(String[] args) throws Exception {
int number = 4;
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
System.out.print("X");
}
System.out.println();
}
}
Solution 2
You need to have separate variables for each of the loops. Otherwise, you'll never run the second iteration of the outer loop. When you're done the inside, your i2
is at the max of the condition of your outer.
Also, you only need the System.out.print()
on the inner loop.
for (int j = 0; j < i; j++) {
for (int k = 0; k < i; k++) {
System.out.print("x");
}
// When you're done printing the "x"s for the row, start a new row.
System.out.print("\n");
}
Solution 3
System.out.println("Give me a number : ");
Scanner kb = new Scanner(System.in);
int size = kb.nextInt();
int height = size;
int width = size;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print("X");
}
System.out.println();
}
The Hacker
Updated on June 14, 2022Comments
-
The Hacker almost 2 years
I am trying to get a for loop inside a for loop so that the output is like this:
I wan the output to show a square
I'm not sure why it isn't doing it. Below is my code:
import java.util.*; public class test { public static void main(String[] args) { System.out.println("Give me a number : "); Scanner kb = new Scanner(System.in); int i = kb.nextInt(); for(int i2=i;i2<i+i;i2++) { System.out.print("x"); for( i2=i;i2<i+i;i2++) { System.out.println("x"); } } } }