2017-01-26 13 views
-2
if ((firstDigit || secondDigit || thirdDigit || fourthDigit || fifthDigit) == 1){ 
     System.out.println(":::||"); 
    } 

これを行う方法はありますか? .equals.compareTo、あるいは私は各変数を実行することによってそれを遅くする必要がありますか?ループ?異なる整数を別の整数と比較するにはどうすればよいですか?

+0

5桁または任意の桁数が必要ですか? –

+0

これらの数字の配列がありますか? – azro

+0

5桁、郵便番号プロジェクト用です。 –

答えて

2

あなたはヘルパーメソッド行うことができます。

static boolean anyMatch(int find, int... in) { 
    for (int n : in) 
     if (n == find) 
      return true; 
    return false; 
} 
// ... 
if (anyMatch(1, firstDigit, secondDigit, ...)) 

それとも、ストリームを使用することができます。

if (IntStream.of(firstDigit, secondDigit, ...).anyMatch(n -> n == 1)) 

それともList.contains()を使用することができます。

if (Arrays.asList(firstDigit, secondDigit, ...).contains(1)) 

しかし、最も単純で最も効率的にオプションはあなたが避けているものです:

もう1つの考慮点は、これらが本当に配列の代わりに異なる変数であるべきかどうかです。

+0

ありがとう!これはうまくいった。 –

1

あなたの構文は合法ではなく、またはの簡潔な形式はありません。あなたはまた、第2の方法は、最初よりもおそらく遅いことIntStream(8+ Javaで)

if (IntStream.of(firstDigit, secondDigit, thirdDigit, fourthDigit, fifthDigit) 
     .anyMatch(x -> x == 1)) { 
    // ... 
} 

のような注意を使用することができ

if (firstDigit == 1 || secondDigit == 1 || thirdDigit == 1 || 
     fourthDigit == 1 || fifthDigit == 1) { 
    // ... 
} 

関連する問題