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

时间:2020-03-01 22:36:54

标签: 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:操作完成。

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以使用allowed: - IPProtocol: tcp ports: - 0-65535 - IPProtocol: udp ports: - 0-65535 - IPProtocol: icmp creationTimestamp: '2020-02-11T11:18:09.906-08:00' description: Allow internal traffic on the default network direction: INGRESS disabled: false id: '1434668200291681054' kind: compute#firewall logConfig: enable: true name: default-allow-internal network: https://www.googleapis.com/compute/v1/projects/myproject/global/networks/default priority: 65534 selfLink: https://www.googleapis.com/compute/v1/projects/myproject/global/firewalls/default-allow-internal sourceRanges: - 10.128.0.0/9 - 10.8.0.0/28

for loop

答案 2 :(得分: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;
    }
}

答案 3 :(得分:0)

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

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