循环验证和输出问题

时间:2016-04-02 04:33:56

标签: java loops

所以我有一切工作,除了一旦我输入所需的输入,我得到这样的输入:

1   5.0
2   6.0
3   7.0
4   8.0

我不知道我做错了什么,因为它似乎没有根据我输入的growRate以50为正增量而增加。也不能让生物数量根据第二天增加。有什么建议吗?

//Purpose of program to predict population of organisms

import java.util.Scanner;

public class Population {
    public static void main(String[] args) {
        double growthRate = -1;
        int population = 0;
        int days = -1;
        double popResult = 0;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("\nEnter the starting number of organisms:");
        population = keyboard.nextInt();

        while (population < 2) {
            System.out.println("\nError!! Please re-enter number of organisms.");
            population = keyboard.nextInt();
        }

        System.out.println("\nEnter rate of growth as percentage:");
        growthRate = keyboard.nextInt() / 100;

        while (growthRate < 0) {
            System.out.println("\nError!! Growth rate must be a positive number. Please re-enter.");
            growthRate = keyboard.nextInt();
        }

        System.out.println("\nEnter number of days organisms will grow:");
        days = keyboard.nextInt();

        while (days < 0) {
            System.out.println("\nError!! Number of days cannot be less than 1. Please re-enter.");
            days = keyboard.nextInt();
        }

        System.out.println("Days" + "\t" + "Organisms");
        System.out.println("------------------");

        popResult = population;
        growthRate = growthRate / 100;

        for (int numberOfDays = 1; numberOfDays < days; numberOfDays++) {
            System.out.println(numberOfDays + "\t" + popResult);
            popResult = (popResult * growthRate) + popResult;

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在以行

中的整数格式输入growRate

growthRate = keyboard.nextInt()/ 100;

如果它小于0,那么你接受输入而不除以100作为

growthRate = keyboard.nextInt();

最后你再次将growthRate除以 growthRate = growthRate / 100;

所以你必须在while循环之外输入 growthRate = keyboard.nextInt();

修改后的代码

automaticallyAdjustsScrollViewInsets = false