0

I need to check if a "user" types in the word "if". Let me explain, i have this: String text;

Scanner read = new Scanner(System.in);
System.out.println("type text");
text=read.nextLine();
System.out.println("the text is " +text);

I need to make sure that what is typed in is a the word "if".

3 Answers 3

2

You need to use String API's contains() or equals() methods as shown below:

if(text.contains("if ") || text.contains(" if") || text.contains(" if ")) {
    System.out.println(" Text contains if");
}

The above code works even if the word if is at the start or at the end of the input text.

If you are looking for the whole word match, then you need to use equals() as shown below:

if(text.equals("if")) {
    System.out.println(" Text equals if");
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to compare the value of text with the value if using equals() like this:

if(text.equals("if")){
   //Do something
}

Or a better null safe solution would be:

if("if".equals(text)){}

This way if text is null your program won't crash Thanks to @Tancho for the null safe sollution Generally speaking to compare 2 string you need to use equals() Using == you compare 2 objects references not the values

1 Comment

Please do "if".equals(text) which is null safe.
0

If you're looking for an exact match, you should use :

"if".equals(text)

Not the other way around, because a constant should always be compared to a variable, not the other way around. You will have : 1. readability 2. safety (as this will never throw a NullPointerException, even if text is null)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.