java - Java - 模拟登录控制台 - 在询问密码之前验证用户名
问题描述
(格式已关闭,无法发布我如何从 Eclipse 复制和粘贴)
我试图在继续询问密码之前验证用户名,我尝试在服务子类中拆分用户名和密码,但这没有用。现在,即使用户名没有存储在 txt 文件中,它也会从用户名直接询问密码,我有它阅读表单。这是我到目前为止所拥有的:
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();
}
}
}
解决方案
由于您尝试在密码之前验证用户名,因此您应该在询问密码之前进行验证。
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();
...
}
推荐阅读
- python - 回滚多行 SQL 事务的潜在问题
- python - TypeError:“地图”对象不可下标 - Python
- css - 如何更改闪亮仪表板布局中的 tabPanel 宽度?
- python - 将 json 对象插入数据湖
- python - 如何将参数仅传递给 PySpark ML Pipeline 对象的一部分?
- android - 如何设置 CompanionDeviceManager.associate() 的超时时间?
- python - Transformer 库缓存路径没有改变
- abap - SAP 获取上次程序运行和使用的参数
- xcode - 错误 ITMS-90596:“无效的捆绑包。无法处理 'Payload/MyApp.app/Assets.car' 处的资产目录。”
- javascript - selectpicker 值如何与其他页面发布 ajax