gpt4 book ai didi

java - 如果输入为 'y' 则重复循环

转载 作者:行者123 更新时间:2023-12-02 07:26:28 24 4
gpt4 key购买 nike

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

最佳答案

将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");

关于java - 如果输入为 'y' 则重复循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com