问题
I'm porting my old Hangman java game to android for my programming finals in january. I've gotten most of it working but i have found that my does not do any checks for invalid characters. The invalid characters are basicly everything but lowercase letters. I have been thinking of manually entering all valid characters into an array and check each input against that. Is there an easier way to do it?
Here is the code that catches the input from the appropriate EditText:
final EditText guessedLetter = (EditText) findViewById(R.id.LetterInput);
final Button enterGuess = (Button) findViewById(R.id.GuessButton);
enterGuess.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String guess = guessedLetter.getText().toString(); //Save text to a string
guessedLetter.setText(""); //Clear EditText after input has been saved to a String
editor.putString(GAME_LOGIC_GUESS, guess);
editor.commit();
Log.i(GAME_DEBUG, "Guess: " + guess + " parsed to guess()");
guess();
checkWin();
updateDisplay();
}
}});
Thanks again!
回答1:
What about using Character.isLowerCase(char ch), or alternatively Character.getType(ch) == LOWERCASE_LETTER
回答2:
You would want to first set a KeyListener using the setKeyListener method of the TextView. You would then override the onKeyDown method of the KeyListener you set and listen for input. If what is typed is NOT a character (ie: A - Z) then you would throw out the input and cancel the event. If what was typed was a character you should convert the character to lowercase before adding it to the text box.
Edit -
Just noticed you're not doing this on key presses but instead the user has to hit "Ok". This makes your life easier.
When the user presses "Ok" check to see if the text is a valid character (ie: Only one character and is between A - Z). If it's not, yell at the user. If it is, either check to see if it's lowercase or conver it to lowercase yourself.
http://developer.android.com/reference/android/widget/TextView.html#setKeyListener(android.text.method.KeyListener)
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Character.html#toLowerCase(char)
回答3:
I found that for this particular problem the easiest solution would be an array filled with only the valid characters. So instead of blacklisting non-valid characters and symbols i simply whitelist the relatively few that are valid.
Here is the array if anyone needs it in the future:
final String[] allowedChars = {"a", "b", "c", "d", "e",
"f", "g", "h", "i", "j",
"k", "l", "m", "n", "o",
"p", "q", "r", "s", "t",
"u", "v", "w", "x", "y",
"z"};
Using a loop for comparing:
for(int n = 0; n < allowedChars.length; n++){
if(allowedChars[n].equalsIgnoreCase(guess)){
//Game logic here
}}
来源:https://stackoverflow.com/questions/4462797/making-sure-edittext-only-returns-single-lowercase-letters