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 || BA が true または B が true (または両方が true) の場合、ステートメントは true です。

あなたの例では、最初の文字が「4」であるとしましょう。

A =ccnString.charAt(0) != '4'偽 (4 != 4 は偽)

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

A || BB が真なので、Sも真です。

于 2014-10-20T06:06:25.267 に答える
3

これは、または( ) の代わりにand ( ) を使用する必要があることを正しく述べている他の多くの回答への追加です。&&||

あなたはド・モルガンの法則にだまされました。それらは、ブール式がどのように否定されるかを定義します。

あなたの例では、有効なユーザー入力を定義する元の式は次のとおりです。

validInput = userPressed3 or userPressed4

しかし、無効なユーザー入力に関心があるため、この式を否定する必要があります。

not(validInput) = not(userPressed3 or userPressed4)

De Morganによると、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);
}

4これにより、で始まらず、かつで始まらない文字列に対してのみエラー メッセージが表示されます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

そうであってはなら&&ない||

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

そう(ccnString.charAt(0) != '4' || ccnString.charAt(0) != '3'でなければいつもtrue

于 2014-10-20T06:05:42.350 に答える
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 に答える