Write a program that asks the user to enter an integer between 1 and 15. If the
ID: 3641581 • Letter: W
Question
Write a program that asks the user to enter an integer between 1 and 15. If the number entered is outside that range, your program should print out an error message and re-prompt for another number. You can use Scanner or JOptionPane.Once the user enters a number in the correct range, your program will print out two patterns of asterisks that look like the following. The number provided by the user is equal to the height of the triangle.
Let us say that the input value was 5.
*
**
***
****
*****
*
**
* *
* *
*****
The only allowable print statements are of those that print only a single asterisk or a single space at once.
Explanation / Answer
Please rate...
import java.util.Scanner;
class pattern
{
public static void main(String args[])
{
int a;
Scanner s=new Scanner(System.in);
do
{
System.out.println(" Enter the number[ between 1 and 15]: ");
a=s.nextInt();
if(a<1 || a>15)System.out.println("Wrong number, enter again: ");
}while(a<1 || a>15);
int i,j;
for(i=1;i<=a;i++)
{
for(j=a;j>=(i+1);j--) //for right alignment
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.print(" ");
}
for(i=1;i<=2;i++)//for 1st 2 lines
{
for(j=a;j>=(i+1);j--) //for right alignment
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.print(" ");
}
for(i=3;i<=a-1;i++)
{
for(j=a;j>=(i+1);j--) //for right alignment
{
System.out.print(" ");
}
for(j=1;j<=i;j++)
{
if(j%2!=0 && i%2==0)System.out.print(" ");
else if(j%2==0 && i%2!=0)System.out.print(" ");
else System.out.print("*");
}
System.out.print(" ");
}
for(j=1;j<=a;j++)
{
System.out.print("*");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.