// Program: Print a triangle of stars
// Given the number of lines, this program prints a triangle of stars.
import java.util.*;
public class TriangleOfStars
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int numberOfLines;
int numberOfBlanks;
int counter = 1;
System.out.print("Enter the number of star lines " + "(1 to 20) to be printed: ");
numberOfLines = console.nextInt();
System.out.println();
while (numberOfLines < 0 || numberOfLines > 20)
{
System.out.println("The number of star lines should " + "be between 1 and 20");
System.out.print("Enter the number of star lines " + "(1 to 20) to be printed: ");
numberOfLines = console.nextInt();
System.out.println ();
}
numberOfBlanks = 30;
for (counter = 1; counter <= numberOfLines; counter++)
{
printStars(numberOfBlanks, counter);
numberOfBlanks--;
}
} // end main
public static void printStars(int blanks, int starsInLine)
{
int count = 1;
for (count = 1; count <= blanks; count++)
System.out.print(" ");
for (count = 1; count <= starsInLine; count++)
System.out.print(" *");
System.out.println();
} //end printStars
}
Sample Output:
Enter the number of star lines (1 to 20) to be printed: 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
In the method main, the user is first asked to specify how many lines of stars to print. (In
this program, the user is restricted to 20 lines because a triangular grid of up to 20 lines fits
nicely on the screen.) Because the program is restricted to only 20 lines, the while loop
in the method main ensures that the program prints the triangular grid of stars only if the
number of lines is between 1 and 20.
No comments:
Post a Comment