【问题标题】:How to repeat input using a while loop with a sentinal如何使用带有哨兵的while循环重复输入
【发布时间】:2018-12-10 07:54:03
【问题描述】:

我需要有关在此代码上放置 while 循环的位置的帮助。几周前我刚开始学习 Java。我想写一个哨兵值-1,如果输入,程序将退出。只要用户输入不是-1,就一直要求重复程序。

当我将 while 循环 "while(currentPop != -1)" 放在第一个问题“输入当前人口”下方时,程序成功运行了它的第一道课程。但是,它并没有回到第一个问题。相反,它直接进入第二个问题,“输入出生率:”。

我应该如何继续并确保第一个问题在循环运行后不断被问到?

谢谢大家!

import java.util.Scanner;

public class Population
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        double birthRate, deathRate;
        double currentPop = 0; 
        double newPop;
        long years;

        System.out.print("Enter current population or -1 to exit: ");
        currentPop = scan.nextDouble();

        System.out.print("Enter birth rate: ");
        birthRate = scan.nextDouble();

        System.out.print("Enter death rate: ");
        deathRate = scan.nextDouble();
        newPop = 0;
        years = 0;          

        System.out.println("===================");
        System.out.println("YEAR     POPULATION");
        System.out.println("===================");

        if (birthRate > deathRate) {
            System.out.printf("0   %,15d\n", (int)currentPop);
            double growthRate = (birthRate - deathRate);
            double doublingTime = Math.log(2) / 
                                Math.log(1 +(growthRate/100)); 
            for (years = 1; years <= (doublingTime+1); years++) {
                newPop = ((growthRate/100) * currentPop) + currentPop;
                currentPop = newPop;
                System.out.printf("%,d   %,15d\n",years,(int)currentPop);
            }
            System.out.printf("\nIt will take %,d years to reach double " 
                            + "the population of %,d\n\n",
                              (int)(doublingTime + 1),(int)currentPop);   
        } else if (birthRate < deathRate) {
            System.out.printf("0   %,15d\n", (int)currentPop);
            double growthRate = (birthRate - deathRate);
            double decreaseTime = Math.log(1/currentPop) 
                                  / Math.log(1 + (growthRate/100));
            for (years = 1; years < (1 + decreaseTime) ; years++) {
                newPop = ((growthRate/100) * currentPop) + currentPop;
                currentPop = newPop;
                System.out.printf("%,d   %,15d\n",years,(int)currentPop);
            }
            System.out.printf("\nPopulation will be zero in %,d years.\n",
                             (int)decreaseTime + 1);
        } else if(birthRate == deathRate) {
        System.out.printf("0   %,15d\n", (int)currentPop);
        double growthRate = (birthRate - deathRate);
        double decreaseTime = Math.log(1/currentPop) 
                              / Math.log(1 + (growthRate/100));
        for (years = 1; years < (1 + decreaseTime) ; years++) {
            newPop = ((growthRate/100) * currentPop) + currentPop;
            currentPop = newPop;
            System.out.printf("%,d   %,15d\n",years,(int)currentPop);
        }
        System.out.printf("\nPopulation is stable.");
    }
}

}

【问题讨论】:

  • Using while loop in java的可能重复
  • 您需要将问题和扫描放在一个循环中,并将答案的处理转移到一个从循环内部调用的单独方法中。
  • 代码中的while循环在哪里?我好像没找到。
  • 你用过调试器吗?为什么不呢?
  • 尝试通过制作更小的示例来学习。对于初学者,请通过minimal reproducible example 提问

标签: java loops while-loop java.util.scanner


【解决方案1】:

要实现while,循环首先要确定终止条件,直到条件达到终止条件(即false),它的语法可以是

while(true) { //your code} 

【讨论】:

  • 问java的问题。为什么要举 C++ 例子?
【解决方案2】:

这是你想要的代码 -

import java.util.Scanner;

public class Population
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        double birthRate, deathRate;
        double currentPop = 0; 
        double newPop;
        long years;

        while(true) {
            System.out.print("Enter current population or -1 to exit: ");
            currentPop = scan.nextDouble();
            if(currentPop == -1)
                break;

            System.out.print("Enter birth rate: ");
            birthRate = scan.nextDouble();

            System.out.print("Enter death rate: ");
            deathRate = scan.nextDouble();
            newPop = 0;
            years = 0;          

            System.out.println("===================");
            System.out.println("YEAR     POPULATION");
            System.out.println("===================");

            if (birthRate > deathRate) {
                System.out.printf("0   %,15d\n", (int)currentPop);
                double growthRate = (birthRate - deathRate);
                double doublingTime = Math.log(2) / 
                                    Math.log(1 +(growthRate/100)); 
                for (years = 1; years <= (doublingTime+1); years++) {
                    newPop = ((growthRate/100) * currentPop) + currentPop;
                    currentPop = newPop;
                    System.out.printf("%,d   %,15d\n",years,(int)currentPop);
                }
                System.out.printf("\nIt will take %,d years to reach double " 
                                + "the population of %,d\n\n",
                                  (int)(doublingTime + 1),(int)currentPop);   
            } else if (birthRate < deathRate) {
                System.out.printf("0   %,15d\n", (int)currentPop);
                double growthRate = (birthRate - deathRate);
                double decreaseTime = Math.log(1/currentPop) 
                                      / Math.log(1 + (growthRate/100));
                for (years = 1; years < (1 + decreaseTime) ; years++) {
                    newPop = ((growthRate/100) * currentPop) + currentPop;
                    currentPop = newPop;
                    System.out.printf("%,d   %,15d\n",years,(int)currentPop);
                }
                System.out.printf("\nPopulation will be zero in %,d years.\n",
                                 (int)decreaseTime + 1);
            } else if(birthRate == deathRate) {
                System.out.printf("0   %,15d\n", (int)currentPop);
                double growthRate = (birthRate - deathRate);
                double decreaseTime = Math.log(1/currentPop) 
                                      / Math.log(1 + (growthRate/100));
                for (years = 1; years < (1 + decreaseTime) ; years++) {
                    newPop = ((growthRate/100) * currentPop) + currentPop;
                    currentPop = newPop;
                    System.out.printf("%,d   %,15d\n",years,(int)currentPop);
                }
                System.out.printf("\nPopulation is stable.");
            }
        }
        scan.close();
    }
}

【讨论】:

    【解决方案3】:

    我认为您应该在第一个问题和其余代码之前添加while(currentPop != -1) {。在该行之后记得设置currentPop = 0 和代码} 的末尾。 编辑: 而且当然 在第一个问题之后 if (currentPop == -1) break;

    【讨论】:

      【解决方案4】:

      退出程序

      直接从main方法返回

      System.out.print("Enter current population or -1 to exit: ");
      currentPop = scan.nextDouble();
      
      if (currentPop == -1.0) {
          return;
      }
      
      System.out.print("Enter birth rate: ");
      

      通过退出或重启循环程序

      在循环构造体中使用breakcontinue

      while (true) {
          System.out.print("Enter current population or -1 to exit: ");
          currentPop = scan.nextDouble();
      
          if (currentPop == -1) {
              break;
          } else if (currentPop <= 0) {
              System.out.println("Population must be positive");
              continue; // restart the loop
          }
      
          System.out.print("Enter birth rate: ");
      
          ...
      }
      System.out.println("Done!");
      

      一个不接受-1的函数

      您可以使用方法抽象出重复的任务(多个输入)

      public static double getValue(Scanner s, String msg) {
        double value = -1;
        while (value == -1) {
          System.out.print(msg);
          value = s.nextDouble();
        }
        return value;
      }
      

      在main方法中

      currentPop = getValue(scan, "Enter current population: ");
      birthRate = getValue(scan, "Enter birth rate: ");
      

      【讨论】:

        【解决方案5】:

        While 循环只会重复它们包含的代码。所以这段代码:

        System.out.print("Enter current population or -1 to exit: ");
        currentPop = scan.nextDouble();
        
        while (currentPop != -1) {
            System.out.print("Enter birth rate: ");
            birthRate = scan.nextDouble();
        
            // the rest of your code
        }
        

        只会重复while循环中的内容。在这种情况下,它只会询问出生率。

        你想要的实际代码是:

        while (true) {
            System.out.print("Enter current population or -1 to exit: ");
            currentPop = scan.nextDouble();
        
            if (currentPop == -1) {
                break;
            }
        
            System.out.print("Enter birth rate: ");
            birthRate = scan.nextDouble();
        
            // the rest of your code
        }
        

        让我们分解一下。

        如果您希望再次询问当前人口,则需要将该行放在 while 循环中。

        我不知道你是否熟悉break,但你说你是新手。 break 所做的是退出它所在的任何循环。这与 while (true) 一起意味着 while 循环将永远运行,除非调用 if 语句。希望对您有所帮助!

        【讨论】:

        • 啊。这为我清除了它!太感谢了!我在 while 块内不写 if 语句太努力了。
        • 很高兴能帮上忙!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-11
        • 2020-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多