Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

313
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda