Do-While 循环中的异常线程

Exception Thread in Do-While Loop

我正在从事一个项目,该项目根据期初余额 (b)、利率 (IR) 和要显示的季度来计算银行账户的价值。我的整个代码运行完美,但最后一部分是确保利率等变量在教授给我的范围内。 如果用户输入超出边界的值并再次询问该值,我确实需要显示一条错误消息。

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

如您所见,几乎所有我的程序都在一个 do-while 循环中。我知道我可以有嵌套循环,但是 在这种情况下我可以在 do-while 循环中放入什么? if-else 语句?尝试抓住障碍?另一个 while 循环?

如果我使用 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);
  }
}

您可以在 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 ... 
}

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

注意:我已经在您的代码中添加了注释。它们中的大多数以 "EDIT:" 开头,这样您就可以知道我更改了什么。我没有在所有情况下都使用这个前缀,因为其中一些是新代码,显然是我的评论

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 数据类型来表示金钱。关于此主题的 Whosebug question 有很好的信息。

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

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

不过,我的做法是这样的。在你的外部 do-while 内部,有三个其他的 do-while 循环来获取三个值。原因是你想一直循环直到得到正确的值。 keyboard.nextLine() 为什么重要的解释包含在 here.

我没有包括你的所有代码,只有有问题的部分。这是我的看法:

import java.util.Scanner;

public class InterestCalculator {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int quartersDisplayed = -1;
        double b = -1.0;
        double IR = -1.0;

        do {
            do {
                System.out.println("Enter the number of quarters.");
                if(keyboard.hasNextInt()) {
                    quartersDisplayed = keyboard.nextInt();
                    keyboard.nextLine(); //important
                } else {
                    System.out.println("You need to enter an integer.");
                    continue;
                }
            } while(quartersDisplayed < 1 || quartersDisplayed > 10);

            do {
                System.out.println("Enter the starting balance.");
                if(keyboard.hasNextDouble()) {
                    b = keyboard.nextDouble();
                    keyboard.nextLine();
                } else {
                    System.out.println("You must enter a number.");
                    continue;
                }
            } while(b <= 0);

            do {
                System.out.println("Enter the interest rate.");
                if(keyboard.hasNextDouble()) {
                    IR = keyboard.nextDouble();
                    keyboard.nextLine();
                } else {
                    System.out.println("You must enter a number.");
                    continue;
                }
            } while(IR <= 0 || IR > 20.0);

            //... rest of code
        } while(true);
    }
}