Do-While循环中的异常线程

时间:2016-10-10 02:37:02

标签: java exception-handling nested-loops do-while

我正在开发一个项目,根据起始余额(b),利率(IR)和要显示的季度计算银行账户的价值。我的整个代码完美无缺,但最后一部分是确保利率等变量在我教授给我的界限范围内。 如果用户在边界外输入值并再次询问该值,我需要显示错误消息。

例如,要显示的季度数需要大于零,且小于或等于10.

正如您所看到的,几乎所有程序都在do-while循环中。我知道我可以有嵌套循环,但是我可以在我的do-while循环中放置什么才能在这种情况下工作?一个if-else声明?尝试并抓住阻止?另一个循环?

如果我使用了try-catch,那么有人能给我一个如何做到这一点的例子吗?非常感谢你的时间,所有的帮助表示赞赏!以下是我的代码供参考。

    import java.util.Scanner;

 public class InterestCalculator
 {
    public static void main(String[] args)
 {
  Scanner scannerObject = new Scanner(System.in);


   Scanner input = new Scanner(System.in);

   int quartersDisplayed;
   double b, IR;


    do
  {
     Scanner keyboard=new Scanner(System.in);
     System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
     quartersDisplayed = keyboard.nextInt();

     System.out.println("Next enter the starting balance. ");
     System.out.println("This input must be greater than zero: ");
     b = keyboard.nextDouble();


     System.out.println("Finally, enter the interest rate ");
     System.out.println("which must be greater than zero and less than or equal to twenty percent: ");
     IR = keyboard.nextDouble();


     System.out.println("You have entered the following amount of quarters: " + quartersDisplayed);         
     System.out.println("You also entered the starting balance of: " + b);
     System.out.println("Finally, you entered the following of interest rate: " + IR);
     System.out.println("If this information is not correct, please exit the program and enter the correct information.");


     double quarterlyEndingBalance = b + (b * IR/100 * .25);
     System.out.println("Your ending balance for your quarters is " + quarterlyEndingBalance);  
     System.out.println("Do you want to continue?"); 
     String yes=keyboard.next("yes");
     if (yes.equals(yes))
     continue;
     else
     break;

        }
        while(true);
  }
}

3 个答案:

答案 0 :(得分:1)

所以这里有一些代码可以回答你的问题并帮助你入门。但是,您的逻辑存在与您的问题无关的问题,我将在之后解决。

注意:我已在您的代码中添加了评论。他们中的大多数都以"编辑开始:"这样你就可以告诉我改变了什么。在所有情况下我都没有使用此前缀,因为其中一些是新代码,而且显然是我的评论

import java.util.Scanner;

public class InterestCalculator {

public static void main(String[] args) {
//      EDIT: you already have a scanner defined below with a more meaningful name so I removed this one
//      Scanner scannerObject = new Scanner(System.in);

        Scanner input = new Scanner(System.in);

        //EDIT: defining userResponse outside the loop so we can use it everywhere inside
        String userResponse = null;

        do {
            //EDIT: moved the variables inside the loop so that they are reset each time we start over.
            //EDIT: initialize your variable to a value that is invalid so that you can tell if it has been set or not.
            int quartersDisplayed = -1;
            //EDIT: gave your variables more meaningful names that conform to java standards
            double startingBalance = -1, interestRate = -1;

            //EDIT: you don't need a second Scanner, just use the one you already have.
//          Scanner keyboard = new Scanner(System.in);

            do{
                System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
                userResponse  = input.next();
                try{
                    quartersDisplayed = Integer.parseInt(userResponse);
                }catch(NumberFormatException e){
                    //nothing to do here, error message handled below.
                }
                if(quartersDisplayed <= 0 || quartersDisplayed > 10){
                    System.out.println("Sorry, that value is not valid.");
                }else{
                    break;
                }
            }while(true);


            do{
                System.out.println("Enter the starting balance (must be greater than zero): ");
                userResponse  = input.next();
                try{
                    startingBalance = Double.parseDouble(userResponse);
                }catch(NumberFormatException e){
                    //nothing to do here, error message handled below.
                }
                if(startingBalance <= 0){
                    System.out.println("Sorry, that value is not valid.");
                }else{
                    break;
                }
            }while(true);


            do{
                System.out.println("Enter the interest rate (greater than zero less than twenty percent): ");
                userResponse  = input.next();
                try{
                    interestRate = Double.parseDouble(userResponse);
                }catch(NumberFormatException e){
                    //nothing to do here, error message handled below.
                }
                //Note: I assume twenty percent is represented as 20.0 here
                if(interestRate <= 0 || interestRate > 20){
                    System.out.println("Sorry, that value is not valid.");
                }else{
                    break;
                }
            }while(true);


            System.out.println("You have entered the following amount of quarters: "
                            + quartersDisplayed);
            System.out.println("You also entered the starting balance of: " + startingBalance);
            System.out.println("Finally, you entered the following of interest rate: "
                            + interestRate);
            System.out.println("If this information is not correct, please exit the program and enter the correct information.");

            double quarterlyEndingBalance = startingBalance + (startingBalance * interestRate / 100 * .25);
            System.out.println("Your ending balance for your quarters is "
                    + quarterlyEndingBalance);
            System.out.println("Do you want to continue?");
            //EDIT: modified your variable name to be more meaningful since the user's response doesn't have to "yes" necessarily
            userResponse = input.next();
//          EDIT: modified the logic here to compare with "yes" or "y" case insensitively.
//          if (userResponse.equals(userResponse))
            if("y".equalsIgnoreCase(userResponse) || "yes".equalsIgnoreCase(userResponse))
                continue;
            else
                break;

        } while (true);

现在解决其他问题 - 您的兴趣计算对我来说似乎不正确。您的公式根本不使用quartersDisplayed变量。我假设你每季度都在复利,所以在计算你的结果时你肯定需要使用它。

这可能超出了您的项目范围,但您不应使用double或float数据类型来表示金钱。有关此主题的stackoverflow question有很好的信息。

可能的改进 - 由于您要求用户提供两个double类型的值,您可以创建一个方法来请求double值并调用它两次而不是重复代码。这是一种更好的方法,因为它有助于减少出错的可能性,并使测试和维护更容易。

答案 1 :(得分:0)

你可以在你的do / while循环中做这样的事情:

do
{
    Scanner keyboard = new Scanner(System.in);

    do
    {
        System.out.println("Enter the numbers of quarters you wish to display that is greater than zero and less or equal to 10: ");
        quartersDisplayed = keyboard.nextInt();
    }
    while (quartersDisplayed < 1 || quartersDisplayed > 10);

    System.out.println("Next enter the starting balance. ");
    do
    {
        System.out.println("This input must be greater than zero: ");
        b = keyboard.nextDouble();
    }
    while (b < 1);

    // rest of code ... 
}

答案 2 :(得分:0)

使用Scanner#hasNextInt(以及$3的等效项),可以避免抛出异常,因此不需要try-catch子句。我认为一般来说,如果你可以避免尝试,它很好,因为它们很笨拙 - 但我可能是错的。

然而,我的方法是这样的。在你的外部锻炼中,有三个其他的do-while循环来获得三个值。原因是您希望保持循环直到获得正确的值。有关double重要原因的解释涵盖here

我没有包含您的所有代码,只包含相关部分。以下是我的看法:

keyboard.nextLine()