user6352932
user6352932

Reputation:

How do you convert the input from a JTextfield from a string to a char?

For Hangman, we have a method checkLetter, which checks to see if the letter the user inputted is in the array char[] that has the word the user is trying to guess for Hangman. Here is the code we have so far:

 public void playGame(String filename)
  {
//a randomword is read from a textfile, and converted from a string to an array of chars that has a char stored in each index

  randomWord = array[(int)(Math.random() * array.length)];
  int length = randomWord.length();

  char[] arr = randomWord.toCharArray();
 }

Then, we have the method checkLetter.

 public boolean checkLetter()
     {
  char inputLetter = letter.charAt(letter.getText()); //letter is the name of the JTextField where the user inputs the letter they are guessing
     }

We are kind of confused as to what to do next, and we would appreciate any help on how to proceed from here. Thank you!

Upvotes: 0

Views: 2486

Answers (1)

meskobalazs
meskobalazs

Reputation: 16041

If the length of the String is (at least) one, you can do this:

String text = letter.getText(); // get the value of the JTextField
char ch = text.charAt(0);       // get the first letter as char

or in one statement, either

char ch = letter.getText().charAt(0);

or

char ch = letter.getText().toCharArray()[0];

Upvotes: 1

Related Questions