一切都很好。但当它到达目的地并询问我是否想再试一次它只是终止程序,我没有输入y或n
编辑:对不起,我应该在发布前更好地查看预览,但似乎在提交时搞砸了代码。这是我的实际代码
import java.util.Scanner;
class MillionDollarYears2
{
public static void main(String[] args)
{
String answer = "y";
double dollars;
final double interest = 0.05;
int year = 0;
Scanner scan = new Scanner(System.in);
while(answer.equals("y") )
{
System.out.println("How many dollars are deposited?");
dollars = scan.nextDouble();
while(dollars < 1000000.00)
{
dollars = dollars + dollars * interest;
year = year + 1;
}
System.out.println("It took " + year + " years to reach your goal.");
System.out.println("Would you like to try again? (y or n)");
answer = scan.nextLine();
}
}
}
答案 0 :(得分:2)
您没有输入正确变量的y / n答案。 您的相关摘要(带有澄清评论):
System.out.println("It took " + year + " years to reach your goal");
answer = scan.nextLine(); // This seems like a mistake
System.out.println("Would you like to try again? (y or n)");
dollars = scan.nextLine(); // This should be saved to answer, which the loop checks against
因此,在更正之后,while循环的结束应该如下所示:
System.out.println("It took " + year + " years to reach your goal");
System.out.println("Would you like to try again? (y or n)");
answer = scan.nextLine();
答案 1 :(得分:0)
它终止是因为在这一行之后:
System.out.println("It took " + year + " years to reach your goal");
answer = scan.nextLine();
answer可能包含一个不是“y”的值并终止while循环。
在你要求再试一次后,你会这样做:
dollars = scan.nextLine();
在该行上将dollars
更改为answer
,然后删除answer = scan.nextLine();
两行。
答案 2 :(得分:0)
将scan.nextLine()
更改为scan.next()
工作程序:
public static void main(String[] args)
{
String answer = "y";
double dollars;
final double interest = 0.05;
int year = 0;
Scanner scan = new Scanner(System.in);
while(answer.equals("y") )
{
System.out.println("How many dollars are deposited?");
dollars = scan.nextDouble();
while(dollars < 1000000.00)
{
dollars = dollars + dollars * interest;
year = year + 1;
}
System.out.println("It took " + year + " years to reach your goal.");
System.out.println("Would you like to try again? (y or n)");
answer = scan.next();
}
}