Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

310
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda