[英]Java - mimic login console - verify username before asking for password
(formatting is off, couldn't post how I copied and pasted from eclipse) (格式化已关闭,无法发布我如何从 Eclipse 复制和粘贴)
I'm trying to verify the username before moving on to ask for password, I tried splitting username and password out in a service subclass, but that didn't work.我试图在继续询问密码之前验证用户名,我尝试在服务子类中拆分用户名和密码,但这没有用。 Right now, it's going right from username to asking for password even if the username is not stored in the txt file I have it reading form.
现在,即使用户名没有存储在 txt 文件中,它也会从用户名到要求输入密码。 Here is what I have so far:
这是我到目前为止所拥有的:
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class LoginConsole {
public static User[] loginUsers = new User[4];
private static UserService userService = new UserService();
public static void main (String[] args) throws IOException {
ReadFile();
Scanner input = null;
try {
input = new Scanner(System.in);
boolean validInput = false;
int attempts = 0;
while (!validInput && attempts != 5) {
System.out.println("Enter your username:");
String username = input.nextLine();
System.out.println("Enter your password:");
String password = input.nextLine();
User found = userService.yesFound(username, password);
if (found != null) {
System.out.println("Welcome: " + found.getName());
validInput = true;
break;
} if(attempts < 4) {
System.out.println("Invalid input, please try again!");
attempts++;
} else {
System.out.println("Too many failed attempts, you are
now locked out!");
break;
}
}
} finally {
if (input != null)
input.close();
}
}
private static void ReadFile() throws IOException, FileNotFoundException {
String verInput = "data.txt";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(verInput));
String currLine;
int i = 0;
while ((currLine = reader.readLine()) != null) {
loginUsers[i] = new User(currLine.split(","));
i++;
}
} finally {
if (reader != null)
reader.close();
}
}
}
Since you're trying to verify username before password, then you should validate before you ask for the password.由于您尝试在密码之前验证用户名,因此您应该在要求输入密码之前进行验证。
System.out.println("Enter your username:");
String username = input.nextLine();
// Validate Username here. (example ..)
User user = userService.findUser(username); // you can create a method dedicated to find user.
if(user != null) {
System.out.println("Enter your password:");
String password = input.nextLine();
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.