首页 > 解决方案 > 更改 askToContinue 方法,使其要求用户输入 Y、y、N 或 n

问题描述

在出现错误消息后让程序继续运行时出现问题。我曾尝试使用不同的 If/Else 或 While 循环来让它工作,但似乎没有任何运气。当前发布的代码在您输入 y、Y、n 或 N 以外的内容之前有效。即使我输入 y、Y、n 或 N,错误消息也会不断弹出。

import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;

public class FutureValueApp {

    public static void main(String[] args) {
        // Avery Owen

        System.out.println("Welcome to the Future Value Calculator\n");

        Scanner sc = new Scanner(System.in);
        String choice = "y";
        while (choice.equalsIgnoreCase("y")) {
            // get the input from the user
            System.out.println("DATA ENTRY");
            double monthlyInvestment = getDoubleWithinRange(sc,
                    "Enter monthly investment: ", 0, 1000);
            double interestRate = getDoubleWithinRange(sc,
                    "Enter yearly interest rate: ", 0, 30);
            int years = getIntWithinRange(sc,
                    "Enter number of years: ", 0, 100);
            System.out.println();

            // calculate the future value
            double monthlyInterestRate = interestRate / 12 / 100;
            int months = years * 12;
            double futureValue = calculateFutureValue(
                    monthlyInvestment, monthlyInterestRate, months);

            // print the results
            System.out.println("FORMATTED RESULTS");
            printFormattedResults(monthlyInvestment, interestRate, 
                    years, futureValue);

            // see if the user wants to continue
            choice = askToContinue(sc);
        }
    }

    public static double getDoubleWithinRange(Scanner sc, String prompt,
            double min, double max) {
        double d = 0;
        boolean isValid = false;
        while (isValid == false) {
            d = getDouble(sc, prompt);
            if (d <= min) {
                System.out.println(
                        "Error! Number must be greater than " + min + ".");
            } else if (d >= max) {
                System.out.println(
                        "Error! Number must be less than " + max + ".");
            } else {
                isValid = true;
            }
        }
        return d;
    }

    public static double getDouble(Scanner sc, String prompt) {
        double d = 0;
        boolean isValid = false;
        while (isValid == false) {
            System.out.print(prompt);
            if (sc.hasNextDouble()) {
                d = sc.nextDouble();
                isValid = true;
            } else {
                System.out.println("Error! Invalid number. Try again.");
            }
            sc.nextLine();  // discard any other data entered on the line
        }
        return d;
    }

    public static int getIntWithinRange(Scanner sc, String prompt,
            int min, int max) {
        int i = 0;
        boolean isValid = false;
        while (isValid == false) {
            i = getInt(sc, prompt);
            if (i <= min) {
                System.out.println(
                        "Error! Number must be greater than " + min + ".");
            } else if (i >= max) {
                System.out.println(
                        "Error! Number must be less than " + max + ".");
            } else {
                isValid = true;
            }
        }
        return i;
    }

    public static int getInt(Scanner sc, String prompt) {
        int i = 0;
        boolean isValid = false;
        while (isValid == false) {
            System.out.print(prompt);
            try {
                i = sc.nextInt();
                isValid = true;
            } catch (InputMismatchException e) {
                System.out.println("Error! Enter a whole number. Try again.");
            }
            sc.nextLine();  // discard any other data entered on the line
        }
        return i;
    }

    public static double calculateFutureValue(double monthlyInvestment,
            double monthlyInterestRate, int months) {
        double futureValue = 0;
        for (int i = 1; i <= months; i++) {
            futureValue = (futureValue + monthlyInvestment) * 
                          (1 + monthlyInterestRate);
        }
        return futureValue;
    }

    public static String askToContinue(Scanner sc) {
        System.out.print("Continue? (y/n): ");
        String choice = sc.next();
        while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
        sc.nextLine();  // discard any other data entered on the line
        System.out.println("Error! Enter y or n. Try again.");
        }
        return choice;
    }

    private static void printFormattedResults(double monthlyInvestment,
            double interestRate, int years, double futureValue) {
        // get the currency and percent formatters
        NumberFormat c = NumberFormat.getCurrencyInstance();
        NumberFormat p = NumberFormat.getPercentInstance();
        p.setMinimumFractionDigits(1);

        // format the result as a single string
        String results
          = "Monthly investment:   " + c.format(monthlyInvestment) + "\n"
          + "Yearly interest rate: " + p.format(interestRate / 100) + "\n"
          + "Number of years:      " + years + "\n"
          + "Future value:         " + c.format(futureValue) + "\n";

        // print the results
        System.out.println(results);
    }
}

标签: java

解决方案


尝试这个:

  public static String askToContinue(Scanner sc) {
        System.out.print("Continue? (y/n): ");
        String choice = sc.next();
        while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")){
        sc.nextLine();  // discard any other data entered on the line
        System.out.println("Error! Enter y or n. Try again.");
        System.out.print("Continue? (y/n): "); //this was missing
        choice = sc.next(); //take the input again
        }
        return choice;
    }

如果输入无效并且不再接受输入,您将陷入 while 循环。


推荐阅读