Alex Vilchis Alex Vilchis - 3 months ago 15
Java Question

Java else if with strings not working - Scanner(System.in);

I am very new in java and to programming overall. Recently I started an IA mock-up program, but my else if line of code is not showing in the terminal, I suppose. However, the if and the else statements do seem to work perfectly.

I'd appreciate any help you can provide.

Sorry for my lackluster English and my inaccurate words.

import java.util.Scanner;
public class IA
{
public static void main(String []args){

Scanner lector= new Scanner(System.in);

System.out.println("Di algo");
String input = lector.next();

if (input.equals ("Hola") || input.equals("hola") || input.equals("ola")){
System.out.println("Hola, humano");
}else if (input==("quien eres")){
System.out.println("Una pobre ilusión de inteligencia artificial");
}else{
System.out.println("Adiós");
}
}
}

Answer

What you are missing is not checking the input value. First check the input value...:

System.out.println(input);

...and see if the value is ok. Then you can say if your "if-else" component is working or not.

Also delete the gap @ input.equals ("Hola"). it must be input.equals("Hola")

Addition: You cannot use == operator for Strings in Java. You can use var.equals("something") to check if variable var equals to "something".

Addition 2: You must use scanner.nextLine() to get typed string completely instead of using scanner.next() because next() gets the next WORD.

And here is your working code: