2013-12-16 45 views
0

它一切都很好。但是当它到达结尾,并询问我是否想再试一次时,它只是终止程序,我不会输入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(); 


    } 

} 

}

回答

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(); 
0

它终止,因为在此之后行:

System.out.println("It took " + year + " years to reach your goal");            
answer = scan.nextLine(); 

答案可能包含一个不是“y”的值并终止while循环。

你问后再次尝试这样做:

dollars = scan.nextLine(); 

变化dollarsanswer该行之前删除answer = scan.nextLine();两行。

0

变化scan.nextLine()scan.next()

工作PROG:

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(); 


    } 

}