使用类的Java登录程序

标签 java authentication

我必须使用公共(public)类和主驱动程序控制台创建一个简单的登录程序。

这是我的代码:

主要

import java.util.Scanner;
public class main  
{

    public static void main(String[] args) 
    {

      Scanner input = new Scanner (System.in);  

      String username;
      String password;


      System.out.println("Welcome to your Social network site!");
      System.out.println("\nEnter your username and password to login to your account.");    

      System.out.println("Username: ");
        username = input.nextLine();

      System.out.println("Password: ");
        password = input.nextLine();

        UserAccount login = new UserAccount(username, password);

        if(login.checkPassword())
            System.out.println("You are logged in!");
        else
            System.out.println("The username and password you entered are incorrect.");
    }


}

用户类别

public class UserAccount 
{

    private String username;
    private String password;
    private String[][] accounts = {{"anthony", "supernova"},{"steve", "java1"}};

    public UserAccount(String username, String password) 
    {
        String user = username;
        String pass = password;
        boolean active;
    }

    public boolean checkPassword()
    {

        if((username.equals(accounts[0][0])) && (password.equals(accounts[0][1])))
            return true;
        else
            return false;
    }

    public void deactivateAccount()
    {
        boolean active = false;
    }

}

问题是我输入正确的信息后不断收到此错误: 线程“main”中的异常 java.lang.NullPointerException at UserAccount.checkPassword(UserAccount.java:19)at main.main(main.java:25)

最佳答案

您没有在 UserAccount 构造函数中分配对象属性。更改如下:

public UserAccount(String username, String password) {
    this.username = username;
    this.password = password;
}

此外,如果您打算使用该 active boolean 值执行某些操作,则还必须将其作为属性添加到您的类中。只是像现在一样在构造函数/方法中声明它不会有任何效果。

关于使用类的Java登录程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25599047/

相关文章:

java - 尝试关闭并由用户输入来更改值

php - 需要帮助用 cookie 完成登录脚本

linux - Linux环境下使用Selenium验证对话框

postgresql - 有没有 pg_shadow 显示密码的原因,但日志显示没有分配密码?

reactjs - react 路由器身份验证重定向

java - 使用 Java 在 Excel 中打开文件

java - 'originalValue.length > size' 怎么会出现在 String 构造函数中?

java - 是否值得合并 byte[] 和 char[] 数组,还是只创建更好

java - 如何在Eclipse中使用Gradle运行Cucumber + Spring Boot应用程序

r - 如何使用服务帐户和 bigrquery 包进行身份验证?