【发布时间】:2014-04-01 21:17:55
【问题描述】:
我遇到了 do-while 循环的问题。它里面有两个 if 语句。该程序应该获取您的用户名和密码(您输入),然后通过再次输入它们来确认它们。当您再次键入它们时,它们必须与您第一次键入它们时相同。当 boolean redo 设置为 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!");
}
}
【问题讨论】:
-
不要为每个输入行创建一个新的 Scanner。您必须重复使用一个扫描仪。
标签: java loops while-loop do-while