我遇到了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!");
}
}
答案 0 :(得分:1)
while(redo = true);
这是一项任务而非比较。这将始终为true
。
while(redo == true);
是您打算键入的内容,但
while(redo);
是你真正想要的,因为它使得无法提交赋值 - 而不是比较错误。
当你比较boolean
以外的常数和变量时,出于同样的原因,最好将常数放在第一位。
if (1 == someInt)
而不是
if (someInt == 1)
如果您不小心使用=
而不是==
,那么常量优先表单将无法编译。
答案 1 :(得分:1)
while(redo = true)
结果始终为true
,因为它等于while(true)
。
=
是作业
==
是比较。