Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
How to read input text ? Java

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".

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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");
}
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

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)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!