gpt4 book ai didi

java - 登录顺序逻辑

转载 作者:行者123 更新时间:2023-11-30 08:02:28 25 4
gpt4 key购买 nike

我有一个代码可以打开一个文件来检查用户提供的用户名或密码是否在该文件中,但是当实际上没有时,该代码显示登录成功。我是编码初学者,所以我需要一些帮助来修复错误并使用没有复杂库或方法的基本初学者编码。

我得到以下输出,这表明我的程序没有按我希望的方式运行:

USERNAME OR PASSWORD INCORRECT! TRY AGAIN
SUCCESSFUL, YOU ARE LOGGED IN!

代码如下:

package login;

import java.io.File;
import java.io.FileNotFoundException;

public class Main {


public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here.
File file = new File("users.txt");
Login newLogin = new Login(file);

newLogin.checkLogin("word", "wordet");
}

}


package login;

import java.io.File;
//library for file exception
import java.io.FileNotFoundException;
import java.util.ArrayList;
//library for opening file
import java.util.Scanner;

public class Login {

private File file;
private ArrayList<String> usernames;
private ArrayList<String> passwords;
private int tries = 3;

public Login(File file) {
this.file = file;
this.usernames = new ArrayList<String>();
this.passwords = new ArrayList<String>();
this.tries = 3;

}

public void readLines() throws FileNotFoundException{

ArrayList<String> lines = new ArrayList<String>();
Scanner input = new Scanner(this.file);
while (input.hasNextLine()){
lines.add(input.nextLine());
}
input.close();

usernames.clear();
passwords.clear();
for(int i = 0; i < lines.size(); i++) {
if (i %2 == 0) {
usernames.add(lines.get(i));
} else {
passwords.add(lines.get(i));
}
}
}

public void checkLogin(String user, String pass) throws FileNotFoundException{
this.readLines();


if (tries == 0){
System.out.println("YOU HAVE TRIED TOO MANY TIMES!");
} else {
for(int i = 0; i < this.usernames.size(); i++) {
if (this.usernames.contains(user)) {
if (passwords.get(i).equals(pass)) {
System.out.println("SUCCESSFUL, YOU ARE LOGGED IN!");
} else {
System.out.println("USERNAME OR PASSWORD INCORRECT! TRY AGAIN");
tries--;
}
}
}
}
}
}

最佳答案

看起来问题出在这段代码中。

           for(int i = 0; i < this.usernames.size(); i++) {
if (this.usernames.contains(user)) {
if (passwords.get(i).equals(pass)) {
System.out.println("SUCCESSFUL, YOU ARE LOGGED IN!");
} else {
System.out.println("USERNAME OR PASSWORD INCORRECT! TRY AGAIN");
tries--;
}
}
}

检查用户名时,您只是查看用户是否存在,而不是当前用户“i”是否与输入的匹配。这应该更改为:

if (usernames.get(i).equals(user)) {

逻辑是:

枚举所有用户。如果当前用户名与测试用户名匹配,请检查密码。如果提供的密码与记录的密码匹配,则登录用户。否则,登录失败。

关于java - 登录顺序逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36925312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com