gpt4 book ai didi

Java登录方法: runs if details are correct but NullPointerException if incorrect

转载 作者:行者123 更新时间:2023-12-01 17:33:28 24 4
gpt4 key购买 nike

我编写了一种方法,使用包含所有用户名和密码的文本文件检查输入的用户名和密码。有趣的问题是,如果详细信息正确,则应用程序将继续进行,但如果详细信息不正确,则会返回 NullPointerException。我的代码如下:

// Checks whether the inputed details are correct
public boolean isCorrect(String u, String p) {
boolean check = false;
String line = null;
try {
do {
line = br.readLine();
// System.out.println("Checking profile : " + line);
String[] info = line.split("\t");
// nested if-statement to improve efficiency over &&
if (info[0].equals(u)) {
System.out.println("username found!");
if (info[1].equals(p)) {
System.out.println("password correct!");
check = true;
} else System.out.println("password incorrect!");
} else System.out.println("username not found!");
} while (line != null && check == false);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return check;
}

返回的 boolean 值被输入到主 Activity 中的以下代码中:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpanel);
Button button = (Button) findViewById(R.id.btnLogin);
Correct = false;



lm = new LoginModel(this);

button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText textUsername = (EditText) findViewById(R.id.textUsername);
EditText textPassword = (EditText) findViewById(R.id.textPassword);

// Collect the login details entered by the user
String username = textUsername.getText().toString();
String password = textPassword.getText().toString();

// Check the application is registering the correct details
System.out.println(username + "\n" + password);

Correct = lm.isCorrect(username, password);

if (Correct) { // if details are correct then start main program
Intent intent = new Intent (LoginView.this, MenuListView.class);
startActivity(intent);
}
else System.out.println("Login is incorrect...");
}
});
}

我不明白的是为什么如果 Correct = true 那么它运行没有问题,但如果 Correct = false 它会使程序崩溃,产生 FATAL EXCEPTION: main,然后是 NullPointerException - 难道它不应该简单地输出System.out.println。

最佳答案

当到达文件末尾时,linenull
因此,您不能在嵌套行中调用 split()(双关语)。

但是,不要使用此代码。这是非常错误的,一旦发布就会轻易泄露密码。

关于Java登录方法: runs if details are correct but NullPointerException if incorrect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8717018/

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