-2

It always give the second conditional regardless of the input. Is (userName == "Charles") the correct way of doing this conditional? or do i need something else.

import java.util.Scanner;
public class Name_input {

      public static void main(String[] args) {
           Scanner input = new Scanner(System.in);

            String userName = input.next();
            System.out.println(userName);

            if (userName == "Charles")
            {
                System.out.println("Correct Name");
            }       
            else if (userName != "Charles")
            {
                System.out.println("Incorrect Name");
            }       
      }

}
c0der
  • 18,467
  • 6
  • 33
  • 65
J.M.C.B
  • 53
  • 1
  • 4

1 Answers1

-2

Is (userName == "Charles") the correct way of doing this conditional

No You don't use "==" to compare strings.

Instead you should be using the equals(...) method:

if ( "Charles".equals( userName ) )

Note I reversed the order of the comparison. This will prevent a NPE if the username is ever null.

System.out.println(userName);

Does that display the expected value? Do you need to use the trim() method?

else if (userName != "Charles")

Also, there is no need for the "else if". The name is either "Charles" or it isn't so you don't need the additional "if" statement.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Not sure why you got all the downvotes, I thought your answer was pretty swell. – RobOhRob Nov 09 '18 at 17:30
  • 2
    @RobOhRob Probably people are DVing a very high-rep user answering an obvious dupe. More on principle than the quality of the answer. – 001 Nov 09 '18 at 17:32
  • Thanks for you answer, i really appreciate it. – J.M.C.B Nov 09 '18 at 19:20
  • @J.M.C.B, glad it helped. Don't forget to "accept" the answer by clicking on the checkmark so people know the problem has been solved. – camickr Nov 09 '18 at 19:25