-2

Hello I am having a some difficulty with a very simple program.

import java.util.*;
public class Compare
{
    public static void main( String args[] )
    {
         String username;
         Scanner input = new Scanner(System.in);
         String users[] = {"John", "James", "Smith", "Paul"};

         System.out.println("Please Enter Username: ");
         username = input.next();

         for( int i = 0; i < users.length(); i ++ )
         {
               if( users[i] == username )
                  System.out.println("Match");
               else
                  System.out.println("No Match");
         }
    }
}

When I run this program I get No Match which I don't know how is possible when I enter the same string as on of the strings in the users array. Any Suggestions?

Mahmoud Abdel-Rahman
  • 497
  • 2
  • 10
  • 27

3 Answers3

1

use .equals method to compare strings ( and any other objects ) not == operator. for instance:

users[i].equals(username);

== operator used with reference variables checks if they are pointing at the same spot in the memory.

Luke
  • 1,236
  • 2
  • 11
  • 16
0

You need to use users[i].equals(username).

== uses reference, not value comparison.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
0

You need to write

if (users[i].equals(username))

Don't use == to compare Strings in Java, because it determines whether two Strings are the exact same object in memory; whereas equals actually compares the characters in the Strings.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110