String menu = JOptionPane.showInputDialog("Enter 'LOGIN', 'REGISTER', or 'EXIT'");
if (menu.equalsIgnoreCase("login") || menu.equalsIgnoreCase("l"))
{
String username = JOptionPane.showInputDialog ("Please enter your username.");
String pinS = JOptionPane.showInputDialog ("Please enter your PIN.");
/* Want to call other class and pass username and pinS
if (LoginVerification (username, pinS) == 1)
loggedIn = true;
else
JOptionPane.showMessageDialog (null, "Account/PIN not found/doesn't match.");
*/
}
这是名为Startup.java的主类的一部分 这是另一个名为LoginVerication.java的类
package bankbalance;
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class LoginVerification
{
public void loginVerification (username, pin)
{
boolean usernameFound = false, pinMatches = false;
try
{
Scanner fileReader = new Scanner (new FileReader ("accounts.txt"));
while (fileReader.hasNextLine() && !usernameFound)
{
usernameFound = fileReader.nextLine().indexOf(username) >= 0; // want username to be passed from other class
}
pinMatches = fileReader.nextLine().indexOf(pin) >= 0; // want pin to be passed from other class
if (usernameFound && pinMatches)
{
return 1; // return 1 to other class
}
else
{
return 0; // return 0 to other class
}
}
catch (FileNotFoundException z)
{
JOptionPane.showMessageDialog (null, "No Accounts found. Please register a new account.");
}
}
}
我该如何正确地做到这一点?我希望从Startup.java调用LoginVerification.java,如果找到用户名并且引脚与用户名匹配,则返回1。谢谢!
答案 0 :(得分:1)
public class LoginVerification {
public static int check(String username, String pin) {
boolean usernameFound = false, pinMatches = false;
try {
Scanner fileReader = new Scanner(new FileReader("accounts.txt"));
while (fileReader.hasNextLine() && !usernameFound) {
usernameFound = fileReader.nextLine().indexOf(username) >= 0; // want username to be passed from other class
}
pinMatches = fileReader.nextLine().indexOf(pin) >= 0; // want pin to be passed from other class
if (usernameFound && pinMatches) {
return 1; // return 1 to other class
}
else {
return 0; // return 0 to other class
}
}
catch (FileNotFoundException z) {
JOptionPane.showMessageDialog(null, "No Accounts found. Please register a new account.");
return 0;
}
}
}
并在调用代码中:
if (LoginVerification.check (username, pinS) == 1)
loggedIn = true;
else
JOptionPane.showMessageDialog (null, "Account/PIN not found/doesn't match.");
答案 1 :(得分:0)
if (LoginVerification.loginVerfication(username, pinS) == 1)
这应该有效。您应该创建方法static
,因为它似乎不依赖于任何特定实例。