import java.util.Scanner;
import java.util.Random;
public class DrawTriangle
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println ("Do you want to see a triangle? Insert y to continue");
String input = scan.next();
boolean cont = false;
if ((input.equals("y")))
{
cont = true;
double a = (40);
double b = (30);
double height = (Math.random() * (b - a + 1) + a);
for (int x = 1; x <= height; x++)
{
for (int y = 0; y < height - x; y++)
{
System.out.print(" ");
}
for (int y = 0; y < x; y++)
{
System.out.print("x ");
}
System.out.println();
}
}
else
{
cont = false;
System.out.println();
System.out.println ("Program ended");
}
}
}
当用户输入'y'时,我需要程序绘制三角形。这是有效的,但是我需要程序然后要求用户再次输入输入,如果用户先前按下'y'。此外,我不确定我的随机数是否正常,因为每次三角形的大小相同......
答案 0 :(得分:1)
将if语句更改为while,在循环中再次询问用户输入,并删除else
while ((input.equals("y")))
{
cont = true;
double a = (40);
double b = (30);
double height = (Math.random() * (b - a + 1) + a);
for (int x = 1; x <= height; x++)
{
for (int y = 0; y < height - x; y++)
{
System.out.print(" ");
}
for (int y = 0; y < x; y++)
{
System.out.print("x ");
}
System.out.println();
}
System.out.println ("Do you want to see a triangle? Insert y to continue");
input = scan.next();
}
System.out.println();
System.out.println ("Program ended");
答案 1 :(得分:1)
您只需将if语句交换为循环,如下所示:
import java.util.Scanner;
import java.util.Random;
public class DrawTriangle
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
boolean cont = false;
String input = "y";
while (input.equals("y"))
{
System.out.println ("Do you want to see a triangle? Insert y to continue");
input = scan.next();
cont = true;
double a = (40);
double b = (30);
double height = (Math.random() * (b - a + 1) + a);
for (int x = 1; x <= height; x++)
{
for (int y = 0; y < height - x; y++)
{
System.out.print(" ");
}
for (int y = 0; y < x; y++)
{
System.out.print("x ");
}
System.out.println();
}
}
cont = false;
System.out.println();
System.out.println ("Program ended");
}
}