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

我最近才开始使用 Java,但我很糟糕。我真的很紧张。我需要弄清楚如何使用do-while循环将 1 到 10 之间的用户输入转换为星号。如果你能告诉我如何做到这一点,我将不胜感激。


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

例子: input = 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);

    }

  }

}


aluckdog
浏览 131回答 2
2回答

汪汪一只猫

这很容易。您需要使用类似counter此处的变量,然后循环直到打印所有星星。最重要的是do while至少运行一次,所以你需要初始化counter为零才能工作。相反,您可以从 1 开始并将条件更改为while (counter <= count)。我希望这是你想要的:&nbsp; &nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; Scanner in = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println( "Enter number between one and ten: " );&nbsp; &nbsp; &nbsp; &nbsp; int count = in.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; } while (counter < count);&nbsp; &nbsp; }

波斯汪

您必须删除if块中的额外行。你的代码很好。import java.util.Scanner;public class JavaApplication12 {&nbsp; public static void main(String[] args) throws Exception {&nbsp; &nbsp; Scanner in = new Scanner(System.in);&nbsp; &nbsp; System.out.println( "Enter number between one and ten: " );&nbsp; &nbsp; int count = in.nextInt();&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; if (count<1||count>10) {&nbsp; &nbsp; &nbsp; System.out.println("Try again");&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; } while (counter < count);&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java