Main topics: Loop Statements Nested Loops Exercise This lab is designed to give
ID: 3679411 • Letter: M
Question
Main topics: Loop Statements
Nested Loops
Exercise
This lab is designed to give you more practice working with loop statements, and in particular, nested
loops.
Problem Description
• For this exercise you will be creating a small Java class that will use a user validation loop to
get a number in the range of 1 to 9, inclusive. Then the program will generate a triangular
shaped figure on the screen, based on the user’s input.
• The triangular shaped figure for an input of 1 is:
11
• The triangular shaped figure for an input of 2 is:
11
2112
• The triangular shaped figure for an input of 3 is:
11
2112
321123
• The triangular shaped figure for an input of n is:
11
2112
321123
. .
. .
. .
n ... 11 ... n
• Once you have written
Explanation / Answer
Below is the desired program.
import java.util.Scanner;
public class ForLoop {
public static void main(String arg[]){
// create a scanner so we can read the command-line input
Scanner scanner = new Scanner(System.in);
// prompt for the user's input
System.out.print("Enter your input for the triangular shaped figure : ");
// get their input as a String
String desiredInputFigure = scanner.next();
// Converted input from String to int.
int desiredNumber = Integer.parseInt(desiredInputFigure);
// Check for input range
if(!(desiredNumber > 0 && desiredNumber < 10)){
System.out.println("The range of the input should be between 1 and 9");
return;
}
System.out.println("The Desired output is : ");
// method to get triangular shape based on input
getTraingulareShape(desiredNumber);
}
// method to get triangular shape based on input
public static void getTraingulareShape(int inputNumber){
for(int i = 1; i <= inputNumber; i++){
for(int j = i; j >= 1; j-- )
System.out.print(j);
for(int j = 1; j <= i; j++ )
System.out.print(j);
System.out.println(" ");
}
}
}
Steps for execute this program:
1. Copy the above program into one file and save it as "ForLoop.java".
1. Start -> Run
2. Enter cmd command in Run popup.
3. cmd window will open and go to the path where ForLoop.java has been saved.
> cd "specify the path here".
4. compile program by using this below command
> javac ForLoop.java
Execute the program by using this below command
>java ForLoop
Output:
Enter your input for the triangular shaped figure : 3
The Desired output is :
11
2112
321123
Note: I have put the validation for the input value. Input value should be between 1 and 9.
If you give input value not in range 1 and 9 then output will be like this.
Output:
Enter your input for the triangular shaped figure : 11
The range of the input should be between 1 and 9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.