1

I was wondering how I can fix this:

import java.util.*;
public class HelloWorld {
  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("What is your name?");
    String name = input.next();
    if (name == Donald)
        System.out.println("Welcome back Admin");
    else
        System.out.println("Go Away");
    }
}

I want to make it so that if the user inputs a specific name, then it will say something specific, anything else and it says go away. I am a new student of Java and was messing around to see if this is possible

Jared
  • 1,449
  • 2
  • 19
  • 40
user3349079
  • 11
  • 1
  • 1
  • 2

1 Answers1

2

If I understand correctly strings are immutable and are frequently reused, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. That means you can't just ask if string1 == string2 because they might be separate instances. So you want to check with string.equals(string2) to 'see if the content is the same'.

import java.util.Scanner;

public class test {
     public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = input.next();
        if (name.equals("Donald"))
            System.out.println("Welcome back Admin");
        else
            System.out.println("Go Away");
        }

}
Matt
  • 3,508
  • 6
  • 38
  • 66