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

问题描述 投票:0回答:4

我的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我计算了您的数字范围:101110

---- jGRASP:操作完成。

java for-loop while-loop nested do-while
4个回答
0
投票

您可以使用for loop

public static void printRange(int minInclusive, int maxInclusive) {
    for (; minInclusive <= maxInclusive; minInclusive++)
        System.out.println(minInclusive);
}

0
投票

所以您要么向上计数,要么向下计数,或者只有一个。

所以

int step = endNum>startNum ? +1 : -1;
int a = startNum;
int b = endNum;
while (a != b) {
    System.out.println(a);
    a = a + step;
}
System.out.println(b);

或将break放在for循环的中间。还有+=,还有一些我们可以做得更常规的事情。

int step = endNum>startNum ? +1 : -1;

for (int i=startNum; ; i+=step) {
    System.out.println(i);
    if (i == endNum) {
        break;
    }
}

0
投票

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

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

0
投票

问题出在使用“ while”和“ >=”的前两个<=循环中。您可以从条件中删除"="

但是您可以按照其他注释的建议来改进代码。

© www.soinside.com 2019 - 2024. All rights reserved.