Reputation: 61
So I need to make a program that has the user input a height and output the following shape with nested loops:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
My idea to get this to work is to use a char as a black space and correspond that to how many spaces I need for the right shape when given the height. However, I am having trouble calling upon it. How do I make the char, run on the same line a certain number of times. I want it to correspond with my 'x' value in the second loop.
import java.util.Scanner;
public class TrueArt
{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
int height;
char star = '*';
// Gets preferred height
System.out.println("Enter the height you want the masterpiece to be: ");
height = sc.nextInt();
for (int i=0; height > i; i--)
{
for (int x = 0; x < height; i++)
{
1 + x * 2
}
}
}
}
Thanks for any advice in advance!
Upvotes: 3
Views: 108
Reputation: 2291
Your for loop
has infinite loop issues. Try to avoid that.
By the way, another pyramid algorithm. Cheers!
for (int i=height; i > 0; i--)
{
if(i!=1) {
for(int y = i-1; y>0; y--) {
System.out.print(" ");
}
}
for (int x = 0; x < 2*(height-i+1)-1; x++)
{
System.out.print("* ");
}
System.out.println();
}
Upvotes: 0
Reputation: 6360
To have the output you want you can use this pyramid algorithm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int height = s.nextInt();
char star = '*';
for(int i = 0;i < height; i++) {
for(int j = 0; j < height - i; j++) {
System.out.print(" ");
}
for(int k = 0; k <= i; k++) {
System.out.print(star + " ");
}
System.out.println();
}
}
You will have to change this a bit to get the specific shape/style pyramid you want but this is something to work off of for learning purpose.
Upvotes: 3