我为身份验证类型的系统拼凑了一些循环,因此有些挣扎。我正在尝试获取代码以重新提示用户如果不输入'q'则退出,它将显示消息,表明他们仍在登录,但又返回到主循环并要求再次输入用户名。我在玩continue和break,但到目前为止,它不会重复内部的If语句。任何指导将不胜感激。
package zooauthfinal;
import java.util.Scanner;
import java.io.File;
import java.security.MessageDigest;
public class ZooAuthFinal {
public static void main (String[] args) throws Exception {
//Creates new scanner for user input
Scanner scan = new Scanner(System.in);
//variable to attempts to track login attempts
int attempts = 0;
//While loop to start collecting user credentials for login
while(true) {
System.out.print("Enter username: ");
String user = scan.nextLine(); //reads user input and assigns to variable "user"
System.out.print("Enter password: ");
String original = scan.nextLine(); //reads user input and assigns to variable "original" for original password
//MD5 conversion script
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
//System.out.println("original:" + original); //Used to check and compare password conversion - shows original user input
//System.out.println("digested:" + sb.toString()); //Used to check and compare password conversion - shows MD5 conversion of original user input
//assigns boolean value to variable "done"
boolean done=false;
//new scanner to read "credentials.txt" file to authenticate user
Scanner file = new Scanner (new File("credentials.txt"));
//While loop to split text file into columns
while(file.hasNextLine ()) {
String record = file.nextLine();
String columns[] = record.split("\t");
//If statement to match value to username
if(columns[0].trim().equals(user)) {
if(columns[1].trim().equals(sb.toString())) {
done=true;
Scanner sc = new Scanner (new File(columns[3].trim() +".txt"));
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
break;
}
}
}
//If statment to start logout procedure, starts when user has been authenticated and user role message has been delivered based on user role
if(done) {
//Instructs user to logout with value 'q'
System.out.println("Type 'q' to logout: ");
String ch = scan.nextLine();
if(ch.toLowerCase().charAt(0) != 'q') {
System.out.println("You are still logged in as " + user +".");
}
//Assigns user input to lowercase value and checks if matches required 'q'
else {
System.out.println("Successfully logged out. Have a nice day!");
}
}
}
//If/else to track number of login attempts (limit 3) and adds 1 to each unsuccessful attempt until 3 attempts, then displays exit protocol
else {
attempts ++;
if(attempts==3) {
System.out.println("Could not verify credentials. Goodbye.\n");
break;
}
//displays login error message on each unsucessful attempt until the third unsuccessful attempt
else {
System.out.println("Invalid username or password, please try again.");
}
}
}
}
答案 0 :(得分:0)
在if(done)块的最后一行添加break语句。
答案 1 :(得分:0)
if(!ch.toLowerCase().equals("q"))