java JOptionPane 字符输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34229448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JOptionPane char input
提问by codeAllDay
I'm working on a hangman program in Java, and part of my code will be to obtain single letter guesses from the user through the JOptionPane dialog box (this is the input method my professor prefers as opposed to the scanner).
我正在用 Java 编写一个刽子手程序,我的部分代码将是通过 JOptionPane 对话框从用户那里获得单个字母的猜测(这是我的教授喜欢的输入法,而不是扫描仪)。
I'm pretty new and have only gotten input from this dialog box as a string then converted the input to an int or double. I've been trying to find a way to get the input as a char but still use the dialog box.
我很新,只从这个对话框中以字符串形式获得输入,然后将输入转换为 int 或 double。我一直在尝试找到一种方法将输入作为字符获取,但仍然使用对话框。
Anyone have a solution or know where I could look to find one?
任何人都有解决方案或知道我可以在哪里找到解决方案?
here's my code so far if you need it for reference.. the last line is where I got stuck
到目前为止,这是我的代码,如果您需要参考的话..最后一行是我卡住的地方
public static void main(String[] args) {
String[] words = {
"javascript", "declaration", "object", "program", "failing"
};
Random rnd = new Random();
String rndWord = words[rnd.nextInt(words.length)];
char[] displayArray = new char[rndWord.length()];
for (int i = 0; i < rndWord.length(); i++) {
displayArray[i] = '_';
}
char[] alphabet = {
'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'
};
String hangman = "Let's Play Hangman!!" + "\n" + "-------------" + "\n" + "|" + "\n" + "|" + "\n" + "|" + "\n" + "|" + "\n" + "|" + "\n" + "|" + "\n" + "|" + "\n" + "|" + "\n" + "\n" + Arrays.toString(displayArray) + "\n" + " ";
JOptionPane.showMessageDialog(null, hangman + " " + Arrays.toString(alphabet) + " ");
String guess = JOptionPane.showInputDialog("Guess a letter: ");
}
回答by Yassin Hajaj
What you could do is loop until the user puts in one and only one character. Then, convert the String
to a char
.
您可以做的是循环,直到用户输入一个且仅一个字符。然后,将 转换String
为char
。
There is no way to return directly a char
from JOptionPane#showInputDialog
(see Oracle's Website)
没有办法直接char
从JOptionPane#showInputDialog
(见甲骨文网站)返回
Solution
解决方案
String guess;
while ((guess=JOptionPane.showInputDialog("Guess a letter: ")).length() != 1);
char charGuessed = guess.charAt(0);
回答by codeAllDay
never mind, I used the following method:
没关系,我使用了以下方法:
//get letter
public static char guess()
{
String guessStr = JOptionPane.showInputDialog
("Enter a letter to guess: ");
// check if have at least one letter
if (guessStr.length() > 0)
{
}
char guessChar = guessStr.charAt(0);
return guessChar;
}