首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用do while循环将用户输入转换为星号?

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

Stack Overflow用户
提问于 2018-10-18 05:29:36
回答 2查看 471关注 0票数 0

我最近刚开始使用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);
    }
  }
}
EN

回答 2

Stack Overflow用户

发布于 2018-10-18 05:34:31

这很简单。你需要在这里使用像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);
    }
票数 1
EN

Stack Overflow用户

发布于 2018-10-18 14:21:02

您必须删除if块中的多余行。您的代码很好。

import java.util.Scanner;

public class JavaApplication12 {
  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");
    }else{

      do {
        System.out.print("*");
        counter++;
      } while (counter < count);
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52863900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档