gpt4 book ai didi

java - 如何使用 do while 循环将用户输入转换为星号?

转载 作者:行者123 更新时间:2023-12-02 10:41:57 25 4
gpt4 key购买 nike

我最近才开始接触Java,而且我的水平很差。我真的压力很大。我需要弄清楚如何使用 do-while 循环将 1 到 10 之间的用户输入转换为星号。如果您能向我展示如何做到这一点,我将非常感激。

System.out.println( "Enter number between one and ten: " );

示例:输入 = 7

预期输出:********

如果数字不在 1 到 10 之间,则显示“重试”并再次询问

public class JavaApplication12  {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println( "Enter number between one and ten: " );
int count = in.nextInt();

int counter = 0;

if (count<1||count>10) {
System.out.println("Try again");
count = in.nextInt();
System.out.print("*");
counter++;
}else{

do {
System.out.print("*");
counter++;
} while (counter < count);
}
}
}

最佳答案

这很容易。您需要使用类似 counter 的变量这里然后循环直到打印出所有星星。最重要的是do while至少运行一次,因此需要初始化 counter到零去工作。相反,您可以从 1 开始并将条件更改为 while (counter <= count) .
我希望这就是您想要的:

    public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.println( "Enter number between one and ten: " );
int count = in.nextInt();
int counter = 0;
do {
System.out.print("*");
counter++;
} while (counter < count);
}

关于java - 如何使用 do while 循环将用户输入转换为星号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52863900/

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