Java 你如何比较角色?

Java 你如何比较角色?,java,random,char,compare,Java,Random,Char,Compare,我只是想问一下如何在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) { p

我只是想问一下如何在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);                  
}
但是,每次我运行我的程序,我输入的每个字母,结果都是Oops!字母更高

请帮帮我。如何正确运行这个程序

谢谢

我会用它来比较字符。它返回一个显示差异的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
 }
使用char1.compareTochar2方法。它会给你你想要的价值

如果需要,请提供更多信息。

尝试以下操作:

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

x和c来自哪里?根据您发布的代码,第二个块c未初始化。请查看小写字母的ASCII值。是的,请尝试使用System.out.println打印x和c。检查值是否在您期望的范围内作为起点,我会将x和c的值添加到输出中以简化调试。x是否包含大写字母?请注意,“Z”<“a”也应该在他写的时候起作用,ASCII值将被比较;我仍然总是得到结果哦!字母高什么值是x,如果是c值是什么?我仍然总是得到结果!比较Ascii值的字母更高,如:如果intx==intc{}Cast并将值存储在单独的int变量中,则比较。比如:inta=intx;intb=intc;然后检查ifa==b{}希望它能工作,或者您可以使用它来获取Ascii值int result=CharUtils.CharToASCIIcharacter;