2016-09-20 88 views
-3

我是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"); 
         } 


        } 
       } 
      } 
     } 

我在想,如果do while循环会更好,但我没有试图让更多的complaicated那么它是什么节目。

+0

目前尚不清楚你描述/观察的实际问题是什么。你能具体吗? – David

+0

@David当我运行该程序时,如果用户键入无效的条目,程序将回答“请输入数量!”,然后程序结束。我希望程序继续执行for循环,直到用户输入有效的条目。 – krillavilla

回答

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等)推向右边),而是有一组简单的有名的方法调用,它们本身描述正在执行的整体操作。