0

My code:

import java.util.HashMap;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Map;
import java.util.*;

public class LeetGrailLogin {
   public static void main(String[] args) {
      Map<String, String> UserPass = new HashMap<String,String>();
      String userinput;
      String[] arrOfStr;
      Scanner sc = new Scanner(System.in);
      UserPass.put("test", "test");

      System.out.println("Please enter your username");
      userinput = sc.nextLine();

      userinput = userinput + ":";

      System.out.println("Please enter your password");
      userinput = userinput + sc.nextLine();

      arrOfStr = userinput.split(":"); 
      if(UserPass.get(arrOfStr[0]) != null) {
         if(arrOfStr[1] == UserPass.get(arrOfStr[0])) {
            System.out.println("Thank you for logging in! Redirecting...");
         }
         else if(arrOfStr[0] != UserPass.get(arrOfStr[0])) {
            System.out.println("Incorrect Passord");
         }
      }
   } 
}

Console:

 ----jGRASP exec: java LeetGrailLogin
Please enter your username
test
Please enter your password
test
Incorrect Passord

 ----jGRASP: operation complete.

I have tried debugging and all values should match up, my code is kind of messy so that may be the cause of the issue.

What I would like to achieve: I would like a user with the username "test" and password "test" to do a mock login by inputing their username and password as asked by the console. If username and password match those already in the hashmap then console says "successful login". If not, console says "incorrect password".

Error that I run into: I cannot for the life of me find the bug that causes the console to print "incorrect password". Can you guys find anything wrong with my code? (I would also appreciate any suggestions about how to clean up my code... it feels super messy to me.) Thanks for any suggestions and help you can provide.

Edit: I am a beginner in Java and I only recently learned hashmaps so if I'm making a somewhat obvious mistake, please be patient with me :D

Ampuja Kid
  • 21
  • 7
  • 2
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) - Specifically `arrOfStr[1] == UserPass.get(arrOfStr[0])` – takendarkk May 26 '20 at 20:24
  • That did fix the bug, thank you! I'll try to stay away from == from now on, and sorry for the basically duplicate question. – Ampuja Kid May 26 '20 at 20:26
  • No worries, it gets asked by a lot of people all the time. – takendarkk May 26 '20 at 20:28

0 Answers0