【问题标题】:How do you compare characters?你如何比较角色?
【发布时间】:2013-10-07 17:39:04
【问题描述】:

我只想问如何在 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);                  
}

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

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

谢谢!

【问题讨论】:

  • xc 来自哪里?从您发布的代码(第二个块)c 未初始化。
  • 查看小写字母的 ASCII 值。
  • 是的,尝试使用 System.out.println 打印 x 和 c。检查值是否在您期望的范围内
  • 作为起点,我会将 x 和 c 的值添加到输出中以简化调试。
  • x 是否包含大写字母?注意'Z' &lt; 'a'

标签: java random char compare


【解决方案1】:

使用char1.compareTo(char2) 方法。它会为您提供您正在寻找的价值。

更多信息here如果你想要的话。

【讨论】:

    【解决方案2】:

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

    例如:

     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
     }
    

    【讨论】:

    • 它应该也可以像他写的那样工作,将比较ASCII值。
    • x 被声明为 > char x;
    • 我仍然总是得到“糟糕!字母更高”的结果
    • x 是什么值,c 是什么值?
    【解决方案3】:

    试试这个:

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

    【讨论】:

    • 我仍然总是得到“糟糕!字母更高”的结果
    • 尝试比较 Ascii 值,例如:if ((int)x ==(int)c) {}
    • 将值转换并存储在单独的 int 变量中,然后进行比较。喜欢:int a= (int) x;int b= (int)c; 然后检查 if(a==b){} 希望它有效,
    • 或者你可以用它来获取Ascii值int result = CharUtils.CharToASCII(character);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2010-09-14
    相关资源
    最近更新 更多