簡體   English   中英

為什么我的密碼do-while循環在Java中不起作用? 我做錯了什么?

[英]Why won't my password do-while loop in Java won't Work? What did I do wrong?

我遇到了do-while循環的問題。 它里面有兩個if語句。 該程序應該使用您的用戶名和密碼(您輸入),然后再次輸入它們來確認它們。 再次鍵入時,必須與第一次鍵入時相同。 當布爾重做設置為false時,do-while循環應該停止(當你正確地重新輸入你的用戶名和密碼時它被設置為false)但是循環繼續,即使它說你有用戶名和密碼正確。 (它表示歡迎,(用戶名))然后循環再次進入,並要求您重新輸入您的用戶名和密碼。 在獲得正確的密碼后如何停止此循環? 請幫忙。

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!"); 
        }
    }
while(redo = true); 

這是一項任務而不是比較。 這將永遠是true

while(redo == true);

是你打算鍵入的,但是

while(redo);

是你真正想要的,因為它使得無法提交賦值 - 而不是比較錯誤。

比較除boolean和變量之外的常量時,最好將常量放在第一位,原因相同。

if (1 == someInt)

代替

if (someInt == 1)

如果你不小心使用=而不是==則常量優先表單將無法編譯。

while(redo = true) 

結果始終為true因為它等於while(true)

=是作業

==是比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM