避免重复使用Java进行系统打印

时间:2018-04-06 16:01:55

标签: java string

我是Java的新手,因此我仍然掌握了基础知识。我有一个任务,我们需要开发一个程序,计算几代后池塘里的鱼群。虽然代码确实起作用并产生了预期的结果,但我想知道是否有办法不必将系统写入打印两次。那就是我有两个实例,程序将给出答案(如果他们选择'f'则为一个,如果他们选择'v'则为一个):

    // Integer declaration
    int istartPop, igrowthRate = 0, igen = 0, igenCount, ifinalPop, ideadFish = 0, MAX_FISH = 5000, imaxFish, MIN_PERCENT = -100, iminPercent, MIN_NO = 0, iminNo;
    imaxFish = MAX_FISH;
    iminPercent = MIN_PERCENT;
    iminNo = MIN_NO;

    // Array declaration
    int[] iaGrowthRate = new int[20];

    // Enabling user to enter data
    Scanner inConsole = new Scanner(System.in);

    // Welcome Text
    System.out.println("Welcome to Population Calculator. \n \nThis program will enable you to calculate the number of fish within a pond. \n \nPlease note: max fish in the pond is " + imaxFish + ".\n");

    // Starting population of fish

    // Assumption: starting population must be between 0 and 5000
    do {
    System.out.println("Enter the starting population of fish");
    istartPop = inConsole.nextInt();
        if (istartPop < iminNo || istartPop > imaxFish)
            System.out.println("Please enter a number between 0 and 5000.");
    } while(istartPop < iminNo || istartPop > imaxFish);

    // Choice of fixed or variable growth rate.
    // Ensure only f or v can be entered

    System.out.println("Enter F for fixed growth, or V for variable");
    String sOption = inConsole.next();


    // Calculation and path based on 'f' choice.
    // Assumption: growth rate must be greater than or equal to -100% to ensure no negative population.     
    if (sOption.equals("F") || sOption.equals("f")) {
        do {
        System.out.println("Enter the growth rate percentage");
        igrowthRate = inConsole.nextInt();
        if(igrowthRate < iminPercent)
            System.out.println("Please enter a growth rate larger than or equal to -100%");
        } while (igrowthRate < iminPercent);

    // Assumption: number of generations must be greater than or equal to 0.
    do {
        System.out.println("Enter the number of generations");
        igen = inConsole.nextInt();
        if (igen < iminNo)
            System.out.println("Please enter a number greater than or equal to 0.");
    } while (igen < iminNo);


        // Calculation loop
    ifinalPop = istartPop;

    for(igenCount = 0; igenCount < igen; igenCount++) {

        ifinalPop += ifinalPop * (int)igrowthRate/100;
        }
    ideadFish = ifinalPop - imaxFish;
        if(ifinalPop > imaxFish) {
            // Output when population is less than or equal to 5000.
            System.out.println ("If you have a starting population of " + istartPop + " and a growth of " + igrowthRate + "%, you will have a final population of " + ifinalPop + " specimens after " + igen + " generations.\nThe habitat capacity of " + imaxFish + " has been reached; " + ideadFish + " fish have died.");
    }
        // Output when population is greater than 5000.
        else {
            System.out.println ("If you have a starting population of " + istartPop + " and a growth of " + igrowthRate + "%, you will have a final population of " + ifinalPop + " specimens after " + igen + " generations.");
        }
    }



        // Calculation and path based on 'v' choice
        else if (sOption.equals("V") || sOption.equals("v")) {

            // Assumption: growth rate must be greater than or equal to -100% to ensure no negative population.

            // Enter growth rate for 1st generation.
            do {
            System.out.println("Enter the growth rate for generation one:");
            iaGrowthRate[0] = inConsole.nextInt();

            if (iaGrowthRate[0] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100% \n");
            } while(iaGrowthRate[0] < iminPercent);

            // Enter growth rate for 2nd generation.
            do {
            System.out.println("Enter the growth rate for generation two:");
            iaGrowthRate[1] = inConsole.nextInt();

            if (iaGrowthRate[1] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[1] < iminPercent);

            // Enter growth rate for 3rd generation.
            do {
            System.out.println("Enter the growth rate for generation three:");
            iaGrowthRate[2] = inConsole.nextInt();

            if (iaGrowthRate[2] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[2] < iminPercent);

            // Enter growth rate for 4th generation.
            do {
            System.out.println("Enter the growth rate for generation four:");
            iaGrowthRate[3] = inConsole.nextInt();

            if (iaGrowthRate[3] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[3] < iminPercent);

            // Enter growth rate for 5th generation.
            do {
            System.out.println("Enter the growth rate for generation five:");
            iaGrowthRate[4] = inConsole.nextInt();

            if (iaGrowthRate[4] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[4] < iminPercent);

            // Enter growth rate for 6th generation.
            do {
            System.out.println("Enter the growth rate for generation six:");
            iaGrowthRate[5] = inConsole.nextInt();

            if (iaGrowthRate[5] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[5] < iminPercent);

            // Enter growth rate for 7th generation.
            do {
            System.out.println("Enter the growth rate for generation seven:");
            iaGrowthRate[6] = inConsole.nextInt();

            if (iaGrowthRate[6] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[6] < iminPercent);

            // Enter growth rate for 8th generation.
            do {
            System.out.println("Enter the growth rate for generation eight:");
            iaGrowthRate[7] = inConsole.nextInt();

            if (iaGrowthRate[7] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[7] < iminPercent);

            // Enter growth rate for 9th generation.
            do {
            System.out.println("Enter the growth rate for generation nine:");
            iaGrowthRate[8] = inConsole.nextInt();

            if (iaGrowthRate[8] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[8] < iminPercent);

            // Enter growth rate for 10th generation.
            do {
            System.out.println("Enter the growth rate for generation ten:");
            iaGrowthRate[9] = inConsole.nextInt();

            if (iaGrowthRate[9] < iminPercent)
                System.out.println("Please enter a growth rate larger than or equal to -100%");
            } while(iaGrowthRate[9] < iminPercent);

            int iNumElts = 10; // capacity for 20, but only using 10 elements here

            ifinalPop = istartPop;

            // Body loop
            for (int iI = 0; iI < iNumElts; iI++) {
                ifinalPop +=  ifinalPop * (int)iaGrowthRate[iI]/100;
            }

            ideadFish = ifinalPop - imaxFish;

            if(ifinalPop > imaxFish) {
                // Output when population is less than or equal to 5000.
                System.out.println ("If you have a starting population of " + istartPop + " and a growth of " + igrowthRate + "%, you will have a final population of " + ifinalPop + " specimens after " + igen + " generations.\nThe habitat capacity of " + imaxFish + " has been reached; " + ideadFish + " fish have died.");
            }
            // Output when population is greater than 5000.
            else {
                System.out.println ("If you have a starting population of " + istartPop + " and a growth of " + igrowthRate + "%, you will have a final population of " + ifinalPop + " specimens after " + igen + " generations.");
            }
        }
}

此外,是否可以验证“请输入f或v”以仅允许这些字符。当我尝试像其他人一样做一个while语句时,它会给出一个错误,即字符串'sOption'需要为其所有其他实例重新初始化。任何帮助都会很棒,谢谢

2 个答案:

答案 0 :(得分:0)

你可以做的是做一个方法

private void print(String message){
   System.out.println(message);
}

并使用您要打印的消息(例如

)调用此方法而不是print语句
print("Please enter a number greater than or equal to 0.");

显然,没有办法实际打印它进行打印。

关于验证,您可以像这样使用String类的matches()方法来检查字符串中是否只有f或v

stringToValidate.matches("(f|v)");

答案 1 :(得分:0)

要不要多次写入特定的println()语句,请将其解压缩到方法中并从您需要的位置调用它。
例如:

System.out.println("Enter the growth rate percentage");

可以被提取到

void printEnterGrowthRate(){
   System.out.println("Enter the growth rate percentage");
}

你可以这样调用方法:

printEnterGrowthRate();

这是删除重复的第一步,但您可以更进一步。

查看这些do语句。

这:

do {
  System.out.println("Enter the growth rate percentage");
  igrowthRate = inConsole.nextInt();
  if(igrowthRate < iminPercent)
    System.out.println("Please enter a growth rate larger than or equal to -100%");
} while (igrowthRate < iminPercent);

和这一个:

do {
  System.out.println("Enter the growth rate for generation one:");
  iaGrowthRate[0] = inConsole.nextInt();
  if (iaGrowthRate[0] < iminPercent)
    System.out.println("Please enter a growth rate larger than or equal to -100% \n");
} while(iaGrowthRate[0] < iminPercent);

和另一个:

do {
  System.out.println("Enter the growth rate for generation two:");
  iaGrowthRate[1] = inConsole.nextInt();
  if (iaGrowthRate[1] < iminPercent)
    System.out.println("Please enter a growth rate larger than or equal to -100%");
} while(iaGrowthRate[1] < iminPercent);

等......(你有11个喜欢!)

几乎所有东西都是重复的。

您应该引入一个返回int的方法,并在每次需要获取增长率的输入时调用它。然后根据具体情况将int分配给igrowthRateiaGrowthRate[]

public int getInputForGrowthRate(String msg, Scanner inConsole){

    do {
       System.out.println(msg);
       int growthRate = inConsole.nextInt();        
       if (growthRate  < MIN_PERCENT)
        System.out.println("Please enter a growth rate larger than or equal to -100%");
    } while(growthRate < MIN_PERCENT);

    return growthRate;
}

您可以替换11组重复的语句来获取输入:

if (sOption.equalsIgnoreCase("f")) {
    int igrowthRate = getInputForGrowthRate("Enter the growth rate percentage", inConsole);
    ...
}

else if (sOption.equalsIgnoreCase("v")) {

    String  commonMsgPartForMultipleInput = "Enter the growth rate for generation : ";

    for (int i=0; i<10; i++){
      iaGrowthRate[i] = getInputForGrowthRate(commonMsgPartForMultipleInput + i, inConsole);
    }
   ...
}