2017-04-12 93 views
0

我正在爲一個項目製作一個銀行機器代碼,並且無論何時登錄都會報錯。這是做它的代碼的部分是這樣的:陷入循環?

if(pincheck == pin){ 
       loggedin = true; 
       pincheck = 0; 
       do{ 
        System.out.println("Welcome, " + name); 
        System.out.println(""); 
        System.out.println("Your account balance is $" + balance); 
        System.out.println(""); 
        System.out.println("Press 1 to deposit funds"); 
        System.out.println("Press 2 to withdraw funds"); 
        System.out.println("Press 3 to log out"); 
        System.out.println(""); 
        options = in.nextInt(); 

        switch (options) { 
         case 1: System.out.println("How much would you like to deposit?");   // deposit 
           deposit = in.nextFloat(); 

           balance = balance + deposit; 
           deposit = 0; 

           System.out.println("You have deposited funds into your account."); // withdraw 
           System.out.println(""); 
          break; 
         case 2: System.out.println("How much would you like to withdraw?"); 
           withdraw = in.nextFloat(); 

           balance = balance - withdraw; 
           withdraw = 0; 

           System.out.println("You have removed funds from your account."); 
           System.out.println(""); 
          break; 
         case 3: System.out.println("Logging out...");        // log out 
           System.out.println(""); 
           loggedin = false; 
          break; 
         default:System.out.println("Please enter a valid number");     // Invalid number 
          break; 
        } 
       }while(loggedin = true); 

正在發生的事情是登錄在你需要把一個號碼,pincheck,如果它等於存在,它會記錄該引腳你可以登錄,但是當我按3登出時,它會打印登出並打印歡迎信息,整個事情再次開始。任何人都可以指出我卡住的地方嗎?

+2

你知道賦值'='和比較等號'=='之間的區別? –

+0

我是一個相對較新的人,如果我只是搜索了一下我認爲會發生的事情,它會告訴我我已經知道的事情。感謝您的幫助,我修復了代碼,它現在正在工作! –

回答

2

=是一個賦值操作符,所以你只是分配值(即,設置loggedin=true),其總是會true(因爲你設置爲true)。

那麼,你是不是檢查循環中的實際情況,所以你需要更正while條件如下圖所示,它使用==運算符(用於評估的條件表達式):

while(loggedin == true); //use == for condition evaluation