使用方法调用y/n答案



我有这段代码。正在调用askToContinue((方法来询问用户是否愿意继续,但我的问题是,无论我输入什么,它都会忽略选择并重新启动程序。我在代码中缺少了什么,导致它忽略了我的选择?

public class FutureValueApp {
public static void main(String[] args) {
System.out.println("Welcome to the Future Value Calculatorn");
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的本地引用。

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

当您在方法内部定义变量时,即使它具有相同的名称,它也不会被方法外部的代码识别。因此,例如,在您的代码中,您有

public static String askToContinue(Scanner sc){
// see if the user wants to conti1nue
System.out.print("Continue? (y/n): ");
String choice = sc.next(); // this choice variable exists only for the 
// askToContinue method
// Once you assign it over here and return it 
// with the code below, you should use the returned 
// value to update the variable choice, which is 
// defined outside your askToContinue method
System.out.println();
return choice;
}

因此,正如其他答案所指出的,如果你这样做了,

choice = askToContinue(sc);

然后代码将运行良好,因为主方法中定义的选择变量将根据您输入的值进行更新

基于John Camerin的答案是,要跳过代码中的双assigning,可以通过在类中定义choice变量来将其设置为全局static变量:

public class FutureValueApp {
public static String choice;
}

或者将其作为方法中的第二个参数发送:

askToContinue(sc,choice);

相关内容

最新更新