Как повторить ввод, используя цикл while с часовым - PullRequest
0 голосов
/ 02 июля 2018

Мне нужна помощь в отношении того, где поместить цикл 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.");
    }
}

}

Ответы [ 5 ]

0 голосов
/ 02 июля 2018

Вот код, который вы хотите -

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();
    }
}
0 голосов
/ 02 июля 2018

Чтобы реализовать некоторое время, сначала нужно определить цикл завершения условия завершения, и оно будет работать до тех пор, пока условие не достигнет условия завершения (т.е. false), его синтаксис может быть как

while(true) { //your code} 
0 голосов
/ 02 июля 2018

Выйти из программы

Просто вернитесь из основного метода

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

if (currentPop == -1.0) {
    return;
}

System.out.print("Enter birth rate: ");

Цикл программы с выходом или перезапуском

Используйте break или continue в теле циклической конструкции

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

В основном методе

currentPop = getValue(scan, "Enter current population: ");
birthRate = getValue(scan, "Enter birth rate: ");
0 голосов
/ 02 июля 2018

Хотя циклы будут повторять только код, который они содержат. Итак, этот код:

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. Надеюсь, это поможет!

0 голосов
/ 02 июля 2018

Я думаю, вы должны добавить while(currentPop != -1) { перед первым вопросом и остальным кодом. После этой строки не забудьте установить currentPop = 0 и в конце кода }. редактировать: И конечно после первого вопроса if (currentPop == -1) break;

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...