【发布时间】:2017-01-05 18:56:19
【问题描述】:
我有一个名为 samplename 的 txt 文件,在该文件中有 3 行值:
samplename
samplepassword
%%%%%%%%%%%%%%%%%
该计划是关于登录注册系统。 当我输入
samplename
在第一个 JTextField 和
samplepassword +
在第二个 JTextField 并按下登录按钮,它应该检查我是否有这样的帐户,如果它有正确的用户名和密码。 Programm 读取内容,只是无法将其与 JTextFields 进行比较。我在做什么错?!?:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class SomeClass
{
public JButton loginButton;
public JTextField login_username;
public JTextField login_password;
String check = null;
String check2 = null;
public static void main(String[] args)
{
SomeClass someClass = new SomeClass();
someClass.doSomething();
}
public void doSomething()
{
loginButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
Scanner scanner = new Scanner(System.in);
BufferedReader rd = null;
String line;
boolean gothrew = false;
boolean ifDOES = false;
String Username;
String Password;
Password = login_username.getText().trim();
Username = login_password.getText().trim();
try
{
rd = new BufferedReader(new FileReader(
"C:\\users\\Dominik Gyarmati\\AppData\\Roaming\\KeepSafe\\users\\"
+ login_username.getText() + ".txt"));
}
catch (FileNotFoundException ex)
{
JOptionPane.showMessageDialog(null, "Your Account doesn't exist");
}
try
{
while ((line = rd.readLine()) != null)
{
if (check == null)
{
check = line;
check.trim();
gothrew = true;
System.out.println(check);
}
else if (gothrew == true)
{
check2 = line;
check2.trim();
System.out.println(check2);
gothrew = false;
ifDOES = true;
}
else if (check.equals(Username) && check2.equals(Password))
{
JOptionPane.showMessageDialog(null,
"You've logged into your account");
check = null;
check2 = null;
ifDOES = false;
}
else
{
JOptionPane.showMessageDialog(null,
"Username or Password is wrong");
check = null;
check2 = null;
ifDOES = false;
}
}
}
catch (IOException ioexex)
{}
}
});
}
}
编辑: 我只需要改变
else if (check.equals(Username) && check2.equals(Password))
到
else if (check.equals(login_username.getText().trim()) &&
check2.equals(login_password.getText().trim())) {
【问题讨论】:
-
为什么
Username是从密码字段的文本中赋值的,反之亦然? -
亲爱的 Dominik Gyarmati,你真的应该关心清理你的示例代码。
-
不是答案,但文件内容的读取应该在第一个块中。如果文件无法打开,您不想阅读。
-
调用 check.trim();不将其分配给变量,是无用的。
-
文件可以打开
标签: java if-statement java.util.scanner bufferedreader