【问题标题】:How do I create this descending line of numbers in Java?如何在 Java 中创建这个递减的数字行?
【发布时间】:2019-01-08 06:23:05
【问题描述】:

我试图在 Java 中创建一个这样的数字递减三角形:

4

3 3

2 2 2

1 1 1 1

用户输入第一个数字,然后它应该创建下降三角形,老实说我不知道​​如何计算出来。

我还没有真正尝试过,我只是迷路了:)

到目前为止,这是我的代码:

public static void numberlines(){
Scanner in = new Scanner(System.in);

System.out.println("Welcome to number lines, enter a number and I'll give you some other numbers in a line...");

    int usernum;
    int counter = 0;
    int count = 0;
    char tab = 9;
    int i;

    usernum = getInt();

    while (counter != usernum){
        if (usernum > counter) { 
            usernum--;
            System.out.println(+ usernum);
        }else if (usernum < counter){
            usernum++;
            System.out.println(+usernum);
        }   
    }//while
}//numberlines  

现在它只打印数字的递减行,但我很确定它还有很多。如果有人有任何很棒的建议或想法。谢谢

【问题讨论】:

  • 了解如何使用嵌套循环。不幸的是,您当前的尝试距离目标还很遥远。
  • 您还可以在图表上绘制数字与每个打印次数的关系,这有一个简单的关系。
  • 是的,我认为它很遥远,作业确实提到了使用嵌套循环
  • @purplepandapoof :好吧,我建议你了解它们并先自己尝试一下,然后如果你遇到困难就回来。

标签: java for-loop methods while-loop


【解决方案1】:

您可以通过嵌套的 while 循环来做到这一点:

  public static void main(String args[]){
        Scanner in = new Scanner(System.in);

        System.out.println("Welcome to number lines, enter a number and I'll give you some other numbers in a line...");

        int usernum;
        int i = 1;
        usernum = in.nextInt();

        while(i <= usernum){
            int j = 1;
            while(j<=i){
                System.out.print(usernum-i+1);
                j++;
            }
            System.out.println();
            i++;
        }//while
    }//numberlines

【讨论】:

    【解决方案2】:

    你可以用这个:

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int usernum = s.nextInt();
        for(int i = 1; i <= usernum; i++){
          for(int j = 1; j <= i; j++){
            System.out.print(usernum-i+1);
          }
          System.out.println();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多