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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (77)

我最近刚开始使用Java,我非常糟糕。我真的很紧张。我需要弄清楚如何使用do-while loop. I would a appreciate it A LOT if you could show me how to do this.

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

example: input = 7

output: *******

if number is not between 1 and ten dislay "try again" and ask again

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);
    }

扫码关注云+社区

领取腾讯云代金券