2016-03-22 85 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); 
    }