Reputation: 107
(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
Upvotes: 3
Views: 22249
Reputation: 165
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');
Upvotes: 0
Reputation: 11173
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'){
...
...
...
}
Upvotes: 0
Reputation: 330
You 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
}
Upvotes: 0
Reputation: 37960
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');
Upvotes: 6