2016-05-11 31 views
0

1から5までの数字のうちの1つを既に持っているので、残りの整数変数を1から5までの範囲で作成したいと考えています。 これまでのところ、数字を見つけるためにif文を使用しましたが、それは非常に時間がかかり、ループを使って可能であると思っていました。私はそれをする方法を理解できないので、私はいくつかの助けが必要です。
はここにある私の文のコードの場合:単一の数字が与えられた他の数字を見つける

int choice1=0; //This can be any number between 1 and 5 inclusive. 
    int temp01 = 0, temp02 = 0, temp03 = 0, temp04 = 0; 
    if(choice1 == 0){ 
     temp01 = 1; 
     temp02 = 2; 
     temp03 = 3; 
     temp04 = 4; 
    } 
    if(choice1 == 1){ 
     temp01 = 0; 
     temp02 = 2; 
     temp03 = 3; 
     temp04 = 4; 
    } 
    if(choice1 == 2){ 
     temp01 = 0; 
     temp02 = 1; 
     temp03 = 3; 
     temp04 = 4; 
    } 
    if(choice1 == 3){ 
     temp01 = 0; 
     temp02 = 1; 
     temp03 = 2; 
     temp04 = 4; 
    } 
    if(choice1 == 4){ 
     temp01 = 0; 
     temp02 = 1; 
     temp03 = 2; 
     temp04 = 3; 
    } 
+0

'for 'ループと配列。 – markspace

+0

あなたは 'for(int i = 0; i <5; i ++)if(i!= choice)System.out.println(i);'? – 11thdimension

+0

forループの作成方法を教えてください。私は配列を作ることができますが、ループは私が立ち往生している部分です。 – blaze077

答えて

0

私の答えはサンジーブが言ったことと同様であるが、私の方法は、このようになります:

  1. 、番号を​​選択してください4つの要素を持つint配列を作成します。 。
  2. forループは0〜4を通過します。
  3. 現在の番号があらかじめ選択された番号である場合は、各繰り返しをオンにします。もしそうなら、何もしないでください。それ以外の場合は、配列の次の未設定の数値を現在の数値に設定します。以下

例:

int numbers[] = new int[4]; 
int counter = 0; 
int preselected = 0; //this would be set to anything from 0-4 
for(int i = 0; i < 5; i++){ 
    if(i != preselected){ 
    numbers[counter] = i; 
    counter++; 
    } 
} 

幸運、およびコーディング幸せ!

0

これらの手順は、

  • がために作成4つの要素を持つ配列を作成して数
  • を選択して、アレイ

    1. を使用して書き込みコードであなたを助けるかもしれません/ whileループは1から5を繰り返します
    2. 入力された数値がループインデックス/カウンタ変数
    3. 等しい場合には、多数の他のスキップアレイとインクリメント列カウンタに追加
    4. インクリメントループカウンタ
    5. プリントアレイ

    ループを作成するためのいくつかの良いチュートリアルを参照

    Loop Control on Tutorials Point

    Nuts and Bolts - For Loop

  • 0

    I wこのようにそれを行うウルド:

    int choice1 = 0; 
    int temp[] = new int[4]; 
    for (int i = 0; i < temp.length; i++) { 
        if (i < choice1) { 
         temp[i] = i; 
        } else { 
         temp[i] = i + 1; 
        } 
    } 
    
    0
    int[] temp = new int[4]; //Here create an array of 4 integers 
    int choice1 = x; // x must be between 0 and 4 included 
    int j = 0; 
    for(int i = 0; i <= 4; i++){ 
        if(!(choice1 == i)){ 
         temp[j] == i; 
         j++; 
        } else if(choice1 != 4){ 
          temp[j] = i+1; 
          i++; 
          j++; 
         } else { 
          temp[j-1] = choice1-1; 
         } 
        } 
    } 
    

    選択が異なっている場合、これは、動作するはずです!(choice1 == i)を使用すると、次を割り当てるので、あなたは、それは同じだ場合は、その値をスキップしたい、位置jにiの値を代入値をtemp [j]にしてループする場合 選択肢が4の場合、IndexOutOfBoundsExceptionが返されます。最後の場合は、前の数値を配列の最後の要素に代入します。

    関連する問題