多个for循环无效输入后重新提示用户

时间:2016-09-20 17:04:24

标签: java

我是Java的初学者,所以请耐心等待,不要因缺乏研究而判断。我在这里

该程序是基本的计算程序。它为用户设计计算项目的总成本。

我的程序调试很好,但问题是当用户输入无效条目时。 一旦用户输入无效条目,for循环就会在Please, enter the amount!

之后结束

我希望程序保持for循环,直到用户输入有效的条目。

import java.util.Scanner;

public class icalculator {

    public static void main(String[] args) {
        Scanner Keyboard = new Scanner(System.in);
        double cost, percentage;
        int years;


        System.out.println("What the estimate cost of the project?");
        cost = Keyboard.nextDouble();

        if (cost <= 0) {
            System.out.println("Please, enter the amount!");
        } else if(cost > 0) {

            System.out.println("What the estimate percentage cost of the project?   ");
            percentage = Keyboard.nextDouble();

            if (percentage <= 0) {
                System.out.println("Please, enter the amount!");
            } else if(percentage > 0) {

                System.out.println("How long it will take to complete the project? \n"
                        + "Please, enter whole numbers.");
                years = Keyboard.nextInt();

                if (years <= 0) {
                    System.out.println("Please, enter the amount!");
                } else if (years > 0) {

这部分是计算区域:

double c = cost;
                        double p = percentage;
                        int y = years;

                        for (int i = 1; i <= 1; i++) {
                            c = Math.round(((p/100) * c) + y);
                            System.out.println("At  " + percentage + "% rate, the cost of the project will be $"
                                    + c + " which take " + years + " years to be complete");
                        }


                    }
                }
            }
        }

我在想是否会做更好的while循环,但我并不是想让程序更加抱怨,那么它是什么。

1 个答案:

答案 0 :(得分:0)

我不确定这个概念是否有更“官方”的术语,但听起来对于任何给定的用户输入,你想要一个“输入循环”,直到提供有效值。 (目前代码无法“返回提示符”,而当检查有效值的if不满足时,逻辑就会结束。)

对于每个输入,它可能看起来像这样:

double cost = 0;
while (cost <= 0) {
    System.out.println("What the estimate cost of the project?");
    cost = Keyboard.nextDouble();

    if (cost <= 0) {
        System.out.println("Please, enter the amount!");
    }
}

毫无疑问,有多种方法可以构建它,但概念是相同的。将变量声明为初始(业务无效)值,重复提示用户,直到该值为业务有效,因此在循环之后您知道您具有有效值。

您可以通过将此过程封装到自己的方法中来进一步指导您的学习/练习,这种方法可以从用户返回您想要的值。您的main()方法会调用另一个方法来获取值。在为每个输入封装此内容之后,请注意相似之处,并查看是否可以将封装的操作重构为单个方法,而不是为每个输入重构一个单独的操作。 (记住要清楚恰当地命名。如果重构后含义发生变化,请更改名称。)

最终,一个理想的结构是远离这些嵌套括号(if s内的if s内的循环,所有这些都向右推),而是有一套简单的 - 命名方法调用,它们自己描述正在执行的整个操作。