【问题标题】:Is this error selection or conditional? (Java)这是错误选择还是有条件的? (爪哇)
【发布时间】:2016-12-29 18:45:52
【问题描述】:

我有一个错误,在第三个 IF 语句中。它检查用户输入的数字是否在 (1-6) 范围内,并且字母是 a-f。我无法测试我的搜索算法,因为该行似乎有错误。我搞不定。似乎有什么问题?是 answer.charAt(1) 吗?

boolean wronganswer = true;
while (wronganswer == true){

    answer = (String)JOptionPane.showInputDialog(null, new JLabel(sb.toString()), "Battleships", JOptionPane.INFORMATION_MESSAGE, pic, null, "");
    if(answer.length() == 2){
        if ((Character.isLetter(answer.charAt(0))) && (Character.isDigit(answer.charAt(1)))){
            if ((answer.charAt(1) >= 0) && (answer.charAt(1) <= 6)){
                for (int k = 0; k < rows.length; k++){
                    if(rows[k] == (""+answer.charAt(0))){
                        wronganswer=false;
                    }
                }
                JOptionPane.showMessageDialog(null,"No! That letter is not on the grid!");
            }
            else{
                JOptionPane.showMessageDialog(null,"No! That number is not on the grid!");
                System.out.println(answer.charAt(1));
            }
        }
        else{
            JOptionPane.showMessageDialog(null,"No! Enter a letter, THEN a number!");
        }
    }
    else{
        JOptionPane.showMessageDialog(null,"No! Enter ONE letter and ONE number!");
    }

}

[编辑] 修复了粘贴到堆栈溢出时的缩进错误

【问题讨论】:

  • charAt(1) 返回字符,而不是数字代表的数字:(answer.charAt(1) &gt;= '0') ...

标签: java if-statement input range selection


【解决方案1】:

这是由于== 将引用与匿名临时java.lang.String 进行比较,后者始终为false。修复很简单;使用

rows[k].equals("" + answer.charAt(0));

而是比较字符串 contents。你可以使用更炫的 Yoda Expression

("" + answer.charAt(0)).equals(rows[k])

如果rows[k]null,则不会抛出NullPointerException

【讨论】:

  • 谢谢!我会改变的。但是,我的意思是比较范围的行(我想我错误地解释了我的问题)。例如,输入的数字是 a3,它会显示“那个数字不在网格上!”当它在范围内时。即使我写 a9 它也是一样的!
  • 已修复!再次感谢
【解决方案2】:

在您的代码中:

if ((answer.charAt(1) >= 0) && (answer.charAt(1) <= 6)){

你会得到一个char。即使你的字符是一个数字,它的值也是它的ASCII value

因此,您的条件实际上不会测试您输入的数字是否介于 0 和 6 之间,但它会测试您的字符是否为 NUL、SOH、STX、ETX、EOT、ENQ 或 ACK。

如果要检查 char 是否为范围内的数字,则必须在范围限制数字周围添加单引号:

if ((answer.charAt(1) >= '0') && (answer.charAt(1) <= '6')){

或者用它们的 ASCII 值替换限制:

if ((answer.charAt(1) >= 48) && (answer.charAt(1) <= 54)){

【讨论】:

  • 这修复了错误!谢谢!然后我收到“字母不在网格上”错误。但是我通过芭丝谢芭的回复修复了它,所以我会给你正确的答案,因为你回答了标题中的问题
猜你喜欢
  • 2012-01-21
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
相关资源
最近更新 更多