Write a JAVA program that asks the user to enter a number. Display the following pattern by writing lines of asterisks.
The first line will have one asterisk, the next two, and so on, with each line having one more asterisk than the previous line,up to the number entered by the user.For example, if the user enters 5, the output would be:
*
* *
* * *
* * * *
* * * * *
1
Expert's answer
2017-01-16T06:46:36-0500
/** * * Write a JAVA program that asks the user to enter a number. * Display the following pattern by writing lines of *asterisks. * The first line will have one asterisk, the next two, and so on, * with each line having one more asterisk than the *previous line, * up to the number entered by the user. * For example, if the user enters 5, the output would be: * * * * * * * * * * * * * * * * * * * * */ import java.util.Scanner; public class Question64581 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter a positive integer number:"); if (sc.hasNextInt()) printAsterisk(sc.nextInt()); else System.out.println("Incorrect number or not a number"); }
public static void printAsterisk(int n) { StringBuilder sb = new StringBuilder("*"); for (int i = 0; i < n; i++) { System.out.println(sb); sb.append(" *"); } } }
Comments
Leave a comment