gpt4 book ai didi

java - 为什么我的字符串检查代码不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:44 25 4
gpt4 key购买 nike

我正在尝试制作一个 JFrame,它检查放置在 JTextField 中的文本是否与 .txt 文件中的信息相同。然后,如果正确,它会检查 JPasswordField 中的信息是否与 .txt 文件中的信息匹配。

public void actionPerformed(ActionEvent e)
{
if(e.getSource() == button)
{
if(!username.getText().equals("") && passIsGood())
{
try
{
Scanner reader = new Scanner(new File("users.txt"));
reader.useDelimiter("\t|\n");
reader.nextLine();
while(reader.hasNextLine())
{
if(reader.next().equals(username.getText()))
{
//Username is correct, now checks for password:
System.out.println("Username passed");
if(reader.next().equals(passToString()))
{
//Username & Password are correct
System.out.println("Password passed");
break;
}
} else if(!reader.hasNextLine())
{
wrongInfo();
} else
{
reader.nextLine();
}
}
reader.close();
frame.dispose();
} catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
} else
{
JOptionPane.showMessageDialog(null, "Please enter a valid Username and Password");
}
}
}

private static String passToString()
{
String passString = new String(password.getPassword());
return passString;
}

我得到了用户名传递的信息,但我觉得 .equals(passToString()) 可能会导致问题。文本文件如下所示:用户名密码测试测试测试2测试3

请注意,每个字段之间的空格是制表符,因此我的分隔符使用 ("\t|\n");

最佳答案

文本字段中包含的字符串可能包含一些不需要的字符。使用字符域(所有作为符号的 ascii 值)来消除这些。试试这个:

import java.io.File;
import java.util.Scanner;

public class readUsers {

public static void main(String[] args) {
try {
Scanner reader = new Scanner(new File("users.txt"));
reader.useDelimiter("\t|\n");

String username = "username";
String password = "password";

for (int i = 0; i < username.length(); i++) {
//replace possible unwanted characters
if (username.charAt(i) < 33 || username.charAt(i) > 126)
username = username.replace(Character.toString(username.charAt(i)), "");
}

for (int j = 0; j < password.length(); j++) {
//replace possible unwanted characters
if (password.charAt(j) < 33 || password.charAt(j) > 126)
password = password.replace(Character.toString(password.charAt(j)), "");
}

while (reader.hasNextLine()) {
String user = reader.next();
String pass = reader.next();

//if username equals the user in the textfile, check if password equals the pass in the file
if (user.equals(username)) {
System.out.println("username passed!");
if (pass.equals(password))
System.out.println("password passed!");
}
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

我的文本文件如下所示:
用户名密码
用户名2密码

附注这是我第一次在 StackOverFlow 上回答,如果我做错了什么请纠正我:)

关于java - 为什么我的字符串检查代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21083783/

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