0
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”,我需要程序然后要求用户再次输入输入。另外我不确定我的随机数是否有效,因为每次三角形的大小都相同......

4

2 回答 2

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");
于 2012-11-22T22:10:04.670 回答
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");

    }
}
于 2012-11-22T22:16:10.957 回答