2016-05-20 28 views
0

對於Hang子手來說,我們有一個checkLetter方法,它檢查用戶輸入的字母是否在數組char []中,該數組中有用戶正在嘗試猜測Hangman的單詞。這裏是我們迄今爲止的代碼:如何將來自JTextfield的輸入從字符串轉換爲char?

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(); 
} 

然後,我們有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 
    } 

我們對接下來要做什麼感到困惑,我們將不勝感激任何關於如何從這裏開始的幫助。謝謝!

+0

能你詳細說明了你所嘗試過的以及哪些失敗了?目前還不清楚你在問什麼。 –

+0

我們正在問如何將輸入從JTextField轉換爲char,而不是字符串。 – wowzacode

+0

爲什麼你在'char []'中存儲這個單詞? – meskobalazs

回答

1

如果String的長度(至少一個),你可以這樣做:

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

或者在一個聲明中,無論是

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

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