Issue
I need a program that continually asks the user if they would like to see a triangle. If the user types "Y" or "y" it prints a triangle made out of x's with a random amount of rows (1-20). After that it continually asks for the answer y again and print another triangle with a different amount of rows until the user types any response which ends the program
this is the code that is needed to be changed so that it continually looks for the answer "Y" or "y" to proceed printing a triangle :
import java.util.Scanner;
public class DrawTriangle {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows of the triangle");
int rows = sc.nextInt();
//iterates for the given number of rows
for (int i = 1; i <= rows; i++) {
//prints the number of spaces before the x
for (int j = rows; j >= i; j--) {
System.out.print(" ");
}
//prints the number of x's in each row
for (int j = 1; j <= i; j++) {
System.out.print("x ");
}
//prints new line for each row
System.out.println();
}
}
}
Solution
Your logic to draw the triangle is working, you should however factor that out to a separate method as you may be calling it multiple times.
To create a random number use new Random().nextInt()
. And for the retries use a while
loop.
import java.util.*;
public class Application {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
var rng = new Random();
System.out.println("Do you want to draw a triangle? [y/Y]");
var answer = sc.nextLine();
while (answer.compareToIgnoreCase("y") == 0){
System.out.println("Do you want to draw a triangle? [y/Y]");
// create random int between 1 (inclusive) and 21 (exclusive)
var rows = rng.nextInt(1, 21);
// print the triangle
printTriangle(rows);
answer = sc.nextLine();
}
System.out.println("Exiting program");
}
public static void printTriangle(int rows) {
//iterates for the given number of rows
for (int i = 1; i <= rows; i++) {
//prints the number of spaces before the x
for (int j = rows; j >= i; j--) {
System.out.print(" ");
}
//prints the number of x's in each row
for (int j = 1; j <= i; j++) {
System.out.print("x ");
}
//prints new line for each row
System.out.println();
}
}
}
Answered By - Mushroomator
Answer Checked By - Senaida (JavaFixing Volunteer)