java - 如何使用Java中的嵌套循环仅打印一次单个数字?

标签 java for-loop while-loop nested do-while

除了代码的最后部分之外,我的 Java 代码中一切都运行良好。所以基本上我不知道如何打印出用户号码(如果它是相同的)。例如,我提示用户输入起始数字和结束数字(整数)。假设用户输入相同的整数“10”作为起始号码,“10”作为结束号码。我希望输出仅为“10”,仅打印一次。我已经尝试了所有我能想到的方法,包括尝试 While 循环、Do-While 循环和 For 循环,但我就是无法弄清楚?

------------------------下面的JAVA代码-------------------- -----------------------

import java.util.Scanner;

public class LoopsAssignment {
   public static void main(String[] args) {

      // input Scanner
      Scanner input = new Scanner(System.in);
      // ask user for a starting number and a ending number
      System.out.println("Now I'll print whatever numbers you'd like!");
      System.out.println("Give me a starting number: ");
      startNum = input.nextInt();
      System.out.println("Give me an ending number: ");
      endNum = input.nextInt();

      // count the users range of numbers
      System.out.println("I counted your range of numbers: ");  
      int a = startNum;
      int b = endNum;

      while (a <= b) {
         System.out.println(a);
         a = a + 1;
      }
         while (a >= b) {
            System.out.println(a);
            a = a - 1;
         }
            while (a == b) {
               System.out.println(a); 
            }    

   }
}

---------------------输出如下---------------------- ------------------------------------------

现在我将打印您想要的任何数字! 给我一个起始号码: 10 给我一个结束号码: 10 我算了一下你的数字范围: 10 11 10

----jGRASP:操作完成。

最佳答案

您可以按如下方式重组代码:

  while (a < b) {
     System.out.println(a);
     a = a + 1;
  }

  while (a > b) {
     System.out.println(a);
     a = a - 1;
  }

  if (a == b) {
     System.out.println(a); 
  }

关于java - 如何使用Java中的嵌套循环仅打印一次单个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480436/

相关文章:

java - 打印阿拉伯数字的简单方法

python - 在 Python 中仅打印以逗号和空格分隔的列表中的数值

java - 调用子对象的方法,其中定义的引用类型属于父对象,但实际引用是子对象

java - 让我的 Canvas 无需大修即可滚动

c - 生成前 50 个可被 7 整除的正整数

java - While 循环表

java - 用 while 循环更新 textView?

java - 当 FileChooser 处于 Activity 状态时防止窗口聚焦

Java动态创建未指定的类

java - While 循环绘制钻石