-1

I am creating a java program that takes in a username and searches an array for a matching username. However, even when the input matches the only username I put in the array, it still will not successfully compare them, saying that the two variables do not match. Here is the code:

import java.util.*;
import java.lang.*;
import java.io.*;
class text
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner user_input = new Scanner( System.in );
        String text;
        System.out.println("Enter Username");
        text = user_input.next( );
        String[] usernames={"Mikey"};
        String username="";
        boolean usernamecorrect=false;
        for(int i=0;i<usernames.length;i++){
            if(usernames[i]==text){
                //With an input of Mikey, this code should run, but doesn't
                System.out.println("Username correct\n");
                usernamecorrect=true;
                username=text;
                break;
            }
        }
        System.out.println(username);
    }
}
Mikey
  • 27
  • 8

1 Answers1

1

try using

usernames[i].equals(text)

instead of

usernames[i]==text

== matches for references only

.equals matches for actual content

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116