java - 使用方法来寻求 y/n 答案

标签 java

我有这个代码。调用askToContinue() 方法来询问用户是否要继续,但我的问题是它只是忽略选择并重新启动程序,无论我输入什么。我在代码中遗漏了什么导致它忽略我的选择?

public class FutureValueApp {

  public static void main(String[] args) {

    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);
        System.out.println();

        askToContinue(sc);
    }
}

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";
        System.out.println(results);
  }

public static String askToContinue(Scanner sc){
    // see if the user wants to conti1nue
    System.out.print("Continue? (y/n): ");
    String choice = sc.next();
    System.out.println();
    return choice;
}

最佳答案

你走在正确的道路上。改变这个

askToContinue(sc);

choice = askToContinue(sc);

因为您需要将askToContinue返回的值分配给名为choice的本地引用。

关于java - 使用方法来寻求 y/n 答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53027760/

相关文章:

apache httpd 启动时出现 Java 问题

java - JPA:即使在 FetchType.LAZY 之后也有 N+1 个查询

java - 预期结果是 <0> 而不是日期

java - 如何在 Java 中比较字符串?

java - 如何在多线程环境下mysql hibernate使用一张表的自增值插入多张表

java - 如何将剪贴板中的文本发送到EditText框

java - 用java监控sql连接信息

java - 获取字符串 "600sp"整数部分的最佳方法?

java - 如何在 Java 中向文件写入新行?

java - 面板不允许添加?