Reputation: 247
import java.util.Scanner;
public class DrawTriangle
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a height");
while (!scan.hasNextInt()) // while non-integers are present
{
scan.next();
System.out.println ("Bad input. Enter an integer.");
}
int input = scan.nextInt();
for (int x = 1; x <= input; x++)
{
for (int y = 0; y < input; y++)
{
System.out.print(" ");
for (int z = 1; z < y; z++)
{
System.out.print("x");
}
System.out.println();
}
}
}
}
I have to make a triangle of x's relating to the height specified by the user. Can't get it to work at all, any help would be appreciated. Thanks!
Sorry should have clarified I need it to look like this -
x
xxx
xxxxx
Upvotes: 1
Views: 2339
Reputation: 213223
You don't need nested loop upto 3 levels. Just 2 levels
are needed. One
for traversing along columns
, and one
for traversing along rows
.
So, change your loop to: -
for (int x = 1; x <= input; x++)
{
for (int y = 0; y < x; y++)
{
System.out.print("x ");
}
System.out.println();
}
UPDATE : -
For equilateral triangle, you would need to add one more loop to print spaces before x
on the starting rows. Here's the code: -
for (int x = 1; x <= input; x++)
{
for (int y = 0; y < input - x; y++) {
System.out.print(" ");
}
for (int y = 0; y < x; y++) {
System.out.print("x ");
}
System.out.println();
}
Upvotes: 2