我有這個代碼。正在調用 askToContinue() 方法來詢問用戶是否愿意繼續(xù),但我的問題是它只是忽略了選擇并無論我輸入什么都再次啟動程序。我在代碼中缺少什么導致它忽略我的選擇?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); }
3 回答

喵喔喔
TA貢獻1735條經(jīng)驗 獲得超5個贊
你在正確的軌道上。改變這個
askToContinue(sc);
到
choice = askToContinue(sc);
因為您需要將返回的值分配給askToContinue
名為choice
.

森欄
TA貢獻1810條經(jīng)驗 獲得超5個贊
您沒有將 askToContinue 的結果分配給在循環(huán)中檢查的選擇變量??赡芑煜氖?askToContinue 方法中的選擇變量。請注意,這是一個不同的變量,不會影響在 while 語句中檢查的選擇變量。

aluckdog
TA貢獻1847條經(jīng)驗 獲得超7個贊
根據(jù) John Camerin 的回答,要assigning在您的代碼中跳過 double ,您可以通過在您的類中定義您的choice變量作為全局static變量:
public class FutureValueApp {
public static String choice;
}
或者將其作為方法中的第二個參數(shù)發(fā)送:
askToContinue(sc,choice);
添加回答
舉報
0/150
提交
取消