1

我只想问如何在 GUI 中使用字母比较字符。这是我随机写一封信的方法:

Random r = new Random();

char c = (char) (r.nextInt(26) + 'a');

然后,当我想将它与输入字母进行比较时,我就是这样做的:

char c;
if(x==c) {
    prompt.setText("Correct!");
    prompt.setForeground(Color.GREEN);
}
else if(x > c) {
    prompt.setText("Oops! Letter is lower");                
    prompt.setForeground(Color.RED);                      
}                  
else if(x < c) {                      
    prompt.setText("Oops! Letter is higher");                     
    prompt.setForeground(Color.RED);                  
}

但是,每次我运行我的程序,我输入一个字母的每个字母,结果都是“哎呀!字母更高”。

请帮帮我。如何正确运行该程序?

谢谢!

4

3 回答 3

0

我会Character.compare(char x, char y)用来比较字符。它返回一个int值来显示差异。然而,一个大问题,什么是变量x?是一个int,另一个char还是完全不同的东西。现在,如果x是一个char变量,那么您可以使用以下内容进行比较:

例如:

 if (Character.compare(x, c) == 0) {
     // they are the same.
 } else if (Character.compare(x, c) >= 0) {
     // x is greater than c
 } else {
     // x is less than c
 }
于 2013-10-01T14:05:11.650 回答
0

使用char1.compareTo(char2)方法。它会给你你正在寻找的价值。

如果您需要,请在此处了解更多信息。

于 2013-10-01T14:06:51.800 回答
0

尝试这个:

Random r = new Random();

        char c = (char) (r.nextInt(26) + 'a');

        if ((int)x ==(int)c) {
            prompt.setText("Correct!");
            prompt.setForeground(Color.GREEN);
        } else if ((int)x >(int)c) {
            prompt.setText("Oops! Letter is lower");
            prompt.setForeground(Color.RED);
        } else if ((int)x <(int)c) {
            prompt.setText("Oops! Letter is higher");
            prompt.setForeground(Color.RED);
        }
于 2013-10-01T14:23:08.083 回答