2016-03-22 51 views
0

年底注册用户输入我有这样的代码:Java的,并不在do-while循环

import java.util.*; 

public class MyAccount { 
    public static double balance = 0.0; 

    public static double deposit(double deposit){ 
     return balance += deposit; 
    } 
    //public void setBalance(double balance){ 
    // this.balance = balance; 
    //} 
    public static void main(String[] args) { 
     Scanner in = new Scanner(System.in); 
     String redo = ""; 
     do{ 
     System.out.println("What do you want to do today?"); 
     String answer= in.nextLine(); 
     if(answer.equals("deposit")){ 
      System.out.println("How much do you want to deposit?"); 
      double money = in.nextDouble(); 
      deposit(money); 
     } 
     System.out.println("Your balance is " + balance); 
     System.out.println("Anything else(Y or N)?"); 
     redo = in.nextLine().toUpperCase(); 
     } while(redo.equals("Y")); 
    } 
} 

程序工作得很好,直到结束。如果我把钱存入并且到达“其他任何东西(Y或N)”?我以后不能进入任何东西;即使我有redo字符串那里。虽然如果我不存钱,我可以输入redo的东西,并且可以让程序循环。我如何修复它,使它即使在我存放了东西时也会循环播放?

回答

5

原因有些棘手。这是因为在拨打in.nextDouble()后,用户的\n仍在输入流中,因此当您拨打redo = in.nextLine().toUpperCase()时,redo将等于空字符串。为了解决这个问题,添加in.nextLine()像这样:

if(answer.equals("deposit")){ 
     System.out.println("How much do you want to deposit?"); 
     double money = in.nextDouble(); 
     in.nextLine(); 
     deposit(money); 
    } 

或者另一种选择是:

if(answer.equals("deposit")){ 
     System.out.println("How much do you want to deposit?"); 
     double money = Double.parseDouble(in.nextLine()); 
     deposit(money); 
    }