0

I'm trying to hide a password for a bank ATM, and i'm getting a null exception for a char[] deceleration. My classmate and professor can't see why I'm getting this thrown at me as everything is correct in the code. The funny thing is it runs fine on repl.it but I get the exception thrown at me on eclipse and netbeans. The int 'pass' is declared earlier in the code and the getPassword() function is declared on another class where it returns an integer password.

I've tried declaring the char[] before assigning it to readPassword() from the console

   //allows you to log in with valid account. not case sensitive
   else if (choice.equals("L") || choice.equals("l"))
   {
     System.out.print("\nPlease enter your id: ");
     id = scnr.nextInt();
     scnr.nextLine();
     Console console = System.console();
     System.out.print("Please enter your password: ");
     char passChar[] = new char[100];
     passChar = console.readPassword();
     String passPars = new String(passChar);
     pass = Integer.parseInt(passPars);

     //verifies id and password
     for (CustomerAccount i : list)
     {
       if (i.getId() == id && i.getPassword() == pass) 
         {
           obj = i;
           check = true;
           break;
          }
     }

Here is the ran code where the expection is thrown at me -- Please enter your id: 123 Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:76) Please enter your password: 123

I expect it to say "Please enter your password: " and you enter the password on that line and it is hidden text in the console.

1 Answers1

3

System.console() often returns null within the IDE. Take a look at the documentation for it:

Returns the unique Console object associated with the current Java virtual machine, if any.

Returns:The system console, if any, otherwise null.

Try using a Scanner instead:

Scanner in = new Scanner(System.in);
String line = in.nextLine();
Malt
  • 28,965
  • 9
  • 65
  • 105
  • I was originally using a scanner but switched to the console because I'm trying to hide the text so that when the user is entering the password it does not show up on the screen. I'm seeing that my problem is the console is returning null but I'm unsure how to make it so that it doesn't. Do i need to push something to the console so that when the system.console() takes place it doesn't return null? – WeepingWillow Oct 08 '19 at 19:07
  • @WeepingWillow Take a look a this answer: https://stackoverflow.com/questions/4203646/system-console-returns-null – Malt Oct 08 '19 at 19:19
  • It’s probably null just in the IDE – Malt Oct 08 '19 at 21:09