2014-04-01 20 views
0

我遇到了一個do-while循環的問題。它有兩個if語句。該程序應該把你的用戶名和密碼(你輸入的),然後再次輸入它們來確認它們。當你再次輸入時,必須與第一次輸入時相同。當布爾重做設置爲false時,do-while循環應該停止(當你正確地重新輸入用戶名和密碼時它會被設置爲false),然而循環繼續進行,即使它說你有用戶名並且密碼正確。 (它說歡迎,(用戶名)),然後循環再次並要求您重新輸入您的用戶名和密碼。獲得正確的密碼後,如何停止此循環?請幫忙。爲什麼我的密碼不能執行Java循環而無法工作?我做錯了什麼?

package Pack1; 
import java.util.Scanner; 
public class class1 { 
    public static void main(String[] args){ 

     String Username; //Used to set the original username 
     String Password; //Used to set the original password 
     String Usernameuse; //Used as a test. This one has to be equal to the original username. 
     String Passworduse; //Used as a test. This one has to be equal to the original password. 
     boolean redo; //This is to determine whether the do-while loop will repeat. 

     Scanner in1 = new Scanner(System.in); //getting the original username 
     System.out.println("Enter your desired username"); 
     Username = in1.nextLine(); 

     Scanner in2 = new Scanner(System.in); //getting original password 
     System.out.println("Enter your desired password"); 
     Password = in2.nextLine(); 

     System.out.println("Identity Confirmation-- Enter your account information"); 

     do{ 
     Scanner in3 = new Scanner(System.in); //gets second username which has to be equal to original 
     System.out.println("Please Enter your Username"); 
     Usernameuse = in3.nextLine(); 

     Scanner in4 = new Scanner(System.in); //gets second password which has to be equal to the original 
     System.out.println("Please Enter your Password"); 
     Passworduse = in4.nextLine(); 

     if(Usernameuse.equals(Username) && Passworduse.equals(Password)){ //determines if both are true 
      System.out.println("Welcome, " + Username); 
      redo = false; //makes redo = false 
     } 
     if(!Usernameuse.equals(Username) || !Passworduse.equals(Password)){ //determines if either one is false 
      System.out.println("Either Username or Password are incorrect, please redo"); 
      redo = true; //makes redo = true 
     } 

     } while(redo = true); //Is supposed to stop looping when you set redo to false, by entering correct username and password 
     System.out.println("You are now on your secret account!"); 
     } 
    } 
+0

不要爲每個輸入行創建一個新的掃描儀。您必須重新使用一臺掃描儀。 –

回答

1
while(redo = true); 

這是一個分配的代替的比較。這將永遠是true

while(redo == true); 

是你想鍵入,但

while(redo); 

是你真正想要的,因爲它使得它不可能犯賦值INSTEAD-OF-比較的誤差。

當您比較boolean和變量之外的常量時,出於同樣的原因,最好先將常量放在第一位。

if (1 == someInt) 

代替

if (someInt == 1) 

如果不小心使用=代替==恆定第一種形式將無法編譯。

+0

你的幫助很有效,謝謝,以及所有寫過(重做)的人。 – user3486889

+0

很高興爲您提供幫助,請在有機會時將此標記爲答案! –

1
while(redo = true) 

結果總是true,因爲它等於while(true)

=是分配

==是比較。

相關問題