-1

So i'm just doing some elementary testing while I learn java, and i'm curious why this doesn't work:

public static void main(String[] args) {
        String[] names={"John","Mark","Suzy","Anthony"};
        String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
        System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
        Scanner x=new Scanner(System.in);
        int y=x.nextInt()-1;
        System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
        Scanner a=new Scanner(System.in);
        String newpass=a.nextLine();
        System.out.println(passwords[y]);
        if(passwords[y]==newpass){
            System.out.print("Hello "+names[y]+"!");
        }else{
            System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
        }
    }

Both passwords[y] and newpass are the exact same string, and when I try:

if(passwords[y]=="passw0rd");

(And obviously pick the 'John') it does work, so i'm hoping someone can explain the difference and how to get around it so as to better accept user input.

Also i'll take a for loop as an answer, but i'm hoping I can avoid it.

TheCodeDR
  • 1
  • 1

2 Answers2

1

never use == to compare strings. Always use equals or equalsIgnoreCase methods. == will check both references pointing to the same object and equals will check the content of the strings.

Gundamaiah
  • 780
  • 2
  • 6
  • 30
  • Huge help. Thanks so much. This did it. It also helped me understand that it checks objects and not the content. I had a feeling it was like that. Thanks again. – TheCodeDR Feb 23 '22 at 03:04
0

Use equals or compareTo method to compare to two Strings instead of == which compares reference.

import java.util.*;

public class Password{
    public static void main(String[] args) {
        String[] names={"John","Mark","Suzy","Anthony"};
        String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
        System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
        Scanner x=new Scanner(System.in);
        int y=x.nextInt()-1;
        System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
        Scanner a=new Scanner(System.in);
        String newpass=a.nextLine();
        System.out.println(passwords[y]);
        if(passwords[y].equals(newpass)){
            System.out.print("Hello "+names[y]+"!");
        }else{
            System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
        }
    }
}

Output:

$ javac Password.java && java Password 
Please indicate which user you would like to log in as:
(1)John
(2)Mark
(3)Suzy
(4)Anthony
1
Please enter the password to log into John's account: passw0rd
passw0rd
Hello John!
Udesh
  • 2,415
  • 2
  • 22
  • 32