任意の int 値にループアップする必要がある場合、値を配列に変換して配列を for-each にするか、従来の for ループを使用する方が良いプログラミング方法ですか?
参考までに、6 面ダイスを複数回投げて、5 と 6 の結果 (「ヒット」) の数を計算しています。私の任意の int 値は、複数のスローの数を表す dicePool です。
私が理解しているように、2つのオプションがあります。
dicePool を配列に変換し、配列を for-each します。
public int calcHits(int dicePool) { int[] dp = new int[dicePool]; for (Integer a : dp) { // call throwDice method } }
従来の for ループを使用します。
public int calcHits(int dicePool) { for (int i = 0; i < dicePool; i++) { // call throwDice method } }
for-each ループはオプション 2 の従来の for ループよりも効率的ですが、オプション 1 は扱いにくいコードであり、不必要に配列を作成する必要があるというのが私の見解です。