-1

I've been trying to make a little program that reads what the user inputs, and if it is correct, the program prints out (user input) + " is a match", and if not, then it says NO MATCH.

The issue that I am having is that even if I input the correct word (cat), it still prints NO MATCH in the console. Would appreciate any help! Thanks :)

Here's the code for what I have:

import java.util.Scanner;

public class StringTester {

    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        String inData;
        System.out.println("Enter a word:");
        inData = stdin.nextLine();
        String response = inData;
        if (response == "cat") {
            System.out.println(response + " is a MATCH");

        } else {
            System.out.println("NO MATCH");

        }
        System.out.println("End of program");
    }
}
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
AadilF1
  • 13
  • 6
  • 2
    use `.equals()` to compare Strings – dumbPotato21 Dec 20 '17 at 16:58
  • Thank you :) did if (response.equals("cat")) and it works brilliantly. P.S. I'm a total newbie with code ! – AadilF1 Dec 20 '17 at 17:00
  • That's absolutely fine. But before adding a question, check if a similar one has already been answered. "How to compare Strings in Java" on google gives a stackoverflow question. This would save you and us a lot of time. – dumbPotato21 Dec 20 '17 at 17:02
  • As a total newbie to coding, I don't really know how to ask questions, like I didn't know it was to do with comparing Strings in Java (sorry!), but I'll definitely try for next time. It's like someone who has a problem with their computer, technicians don't always know the answer to every problem, a lot of them google the problems, but being able to know what questions to ask google is a skill in itself :) – AadilF1 Dec 20 '17 at 17:08

1 Answers1

0

The mistake is that you compare object references response == "cat" instead of checking the value of the object: response.equalsIgnoreCase("cat")

  • 2
    You should avoid answering duplicate questions. From the next time, flag the question as duplicate. – dumbPotato21 Dec 20 '17 at 17:04
  • The question was not about comparing strings, but about what is wrong with the code. For example another mistake would have been to compare the string with "cat\n" or "cat\n\r". Philosophically, all basic Java questions can be replied with "answer is in the documentation, see https://docs.oracle.com/javase/9/index.html". –  Dec 20 '17 at 17:35