0

我正在做这个小程序,但不幸的是我遇到了这个问题..

  if (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3') { 
      System.out.println("The String entered does not fit any of the Credit card standards");
      System.exit(0);
  }

如果我在我的字符串中放入任何整数,我的程序无法识别。

但是,如果我删除我的 || 最后一部分,if 语句识别第一个整数。

我在这里想念什么?

4

5 回答 5

7
if (ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3')

总是true

每个角色都是!= '4'!= '3'

我猜你想要&&

细节:

A || B如果 A 为真或 B 为真(或两者都为真),则该陈述为真。

在您的示例中,假设第一个字符是“4”。

A =ccnString.charAt(0) != '4'是假的(4 != 4 是假的)

B =ccnString.charAt(0) != '3'为真(3 != 4 为真)

所以A || B是真的,因为 B 是真的。

于 2014-10-20T06:06:25.267 回答
3

这是对许多其他正确说明您必须使用and ( &&) 而不是or ( ||) 的答案的补充。

你被德摩根的法律愚弄了。它们定义了布尔表达式如何被否定。

在您的示例中,定义有效用户输入的原始表达式如下:

validInput = userPressed3 or userPressed4

但是由于我们对无效的用户输入感兴趣,所以必须否定这个表达式:

not(validInput) = not(userPressed3 or userPressed4)

按照德摩根的说法,not(A or B)等于not(A) and not(B)。所以我们也可以这样写:

not(validInput) = not(userPressed3) and not(userPressed4)

换句话说:这是德摩根的错!;)

于 2014-10-20T06:36:59.750 回答
2

你可能想要

if (ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3') {
    System.out.println("The String entered does not fit any of the Credit card standards");
    System.exit(0);
}

这只会为不以4AND 不以开头的字符串提供错误消息3

4您的原始条件会为任何不以或不以开头的字符串给出错误3,并且由于所有字符串都满足该条件,因此您将始终收到错误消息。

如果您在初始测试后需要附加条件,您可以执行以下操作:

if (ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3') {
    System.out.println("The String entered does not fit any of the Credit card standards");
    System.exit(0);
} else if (ccnString.charAt(0) == '3' && ccnString.charAt(1) == '7') {
     // here you know that ccnString starts with 37
} else if (...) {
    ...
}
... add as many else ifs as you need ...
else {
    // default behavior if all previous conditions are false
}
于 2014-10-20T06:05:32.483 回答
1
 if ((ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3')
                || (ccnString.charAt(0) == '3' && ccnString.charAt(1) == '7')) {
            System.out.println("The String entered does not fit any of the Credit card standards");
            System.exit(0);
        }
于 2014-10-20T06:14:41.710 回答
1

应该&&不是||

ccnString.charAt(0) != '4' && ccnString.charAt(0) != '3'

否则(ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3'总是true

于 2014-10-20T06:05:42.350 回答