(Beginner with java here),
I'm making a simple game where the user can type if he wants to play again or not. However, I want the game to keep replaying as long as he types yes, Yes or any combination of yes. So As long as the first letter is y the game continues. Ex)
Game Runs
} while(newGame.charAt (0) == 'y'); But I also want java to ignore if it is Y or y, I tried combining charAt(0) == 'y' and IgnoreCase but couldn't figure it out.
I know I could just do && 'Y', but seems like it is unnecessary code?
Thanks
24 Answers
A neat trick for case insensitivity is to simply convert to lowercase before you compare. The class Character contains a number of useful functions for manipulating characters, so you can do this:
} while (Character.toLowerCase(newGame.charAt(0)) == 'y'); 0You should use the method String.startsWith. Its name is explaining what it is doing. To ignore case sensitivity, you can use String.toLowerCase (or toUpperCase respectivly).
This will result in the following:
if (newGame.toLowerCase().startsWith("y")) { // Play again } Based on the logic you described here I think you should use || instead of &&.
And for ignoring case sensitivity you can Use Character's class static method toUpperCase() or toLowerCase(). Example -
while(Character.toUpperCase(newGame.charAt (0)) == 'Y'){ ... ... ... } You could ignore the case sensitivity by simply converting the character to lower case or upper case using toLowercase() or toUppercase() methods.
while(Character.toLowerCase(newGame.charAt(0)) == 'y'); while(Character.toUpperCase(newGame.charAt(0)) == 'y');