使用方法调用任意答案

我有这个代码。正在调用 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);

  }




动漫人物
浏览 154回答 3
3回答

喵喔喔

你在正确的轨道上。改变这个askToContinue(sc);到choice = askToContinue(sc);因为您需要将返回的值分配给askToContinue名为choice.

森栏

您没有将 askToContinue 的结果分配给在循环中检查的选择变量。可能混淆的是 askToContinue 方法中的选择变量。请注意,这是一个不同的变量,不会影响在 while 语句中检查的选择变量。

aluckdog

根据 John Camerin 的回答,要assigning在您的代码中跳过 double ,您可以通过在您的类中定义您的choice变量作为全局static变量:public class FutureValueApp {public static String choice;}或者将其作为方法中的第二个参数发送:askToContinue(sc,choice);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java