It asks the user if he wants to continue playing, takes the first letter of the answer, and if it is an "s" or an "S" the boolean gives TRUE, but for some reason if instead of writing the user YES or if he writes "continue " returns FALSE and exits. The idea is that even if you answer something with spaces, it only takes the first letter.
the idea is to allow: YES, yes, follow, Follow, s (any word that begins with the letter "S" or "s").
System.out.println("¿Volver a jugar?(si/no): ");
volverjugar = teclado.nextLine();
String primera=volverjugar.substring(0, 1);
boolean seguir;
seguir = (primera == "s" || primera == "S");
System.out.println(seguir);
In Java you have to use
equals
to compare if the contents of two strings are equal. The operator==
will only be true if the objects are equal, that is, if they point to the same reference.So your code should work:
As @JackNavaRow says, you can do a unique comparison by converting the data to uppercase.
Or, if you want to simplify, since you are only interested in comparing the first letter, you can use
charAt()
combining withCharacter.toUpperCase
, in that case, you do have to use==
because it would be a comparison of primitive types (pay attention here to the use of single quotes for'S'
:Or, as @x3k_js has said, you can fall back to
equalsIgnoreCase
. In this example, we usecharAt
to get just the first character, convert it toString
so we can then do a comparison based onequalsIgnoreCase
:what happens is that you are comparing a String with another and as the colleagues say it is with equals.
If you want to do it with == you can compare with char :
I hope it helps you, hug.