2016-04-29 7 views
3

theBoardの特定の領域に特定の値のthePlayerがあるかどうかを確認します。配列内の特定のポイントに特定のcharがあるかどうかを調べる方法はありますか?

public boolean diagonal(char[][] theBoard, char thePlayer) { 
    int x = 0; 

    while (x <theBoard.length){ 
     if (thePlayer == theBoard[x][x]) { 
     x++; 
     } 
     else { 
     return false; 
     } 
    } 
+1

ループが必ずしも終了するとは限りません。 – Gendarme

+0

@Gendarmeなぜですか? –

+0

Nvm。私の悪い。私は誤解しました。 – Gendarme

答えて

1

多次元配列を使用しているため、ネストされたforループを使用してみてください。

public boolean diagonal(char[ ][ ] theBoard, char thePlayer) { 
    boolean result = false; 
    int x, y; // These will tell you the coordinates of thePlayer if found on theBoard 

    for(int i = 0; I < theBoard.length; i++) 
     for(int j = 0; j < theBoard[i].length; j++) 
      if (thePlayer == theBoard[i][j]) { 
       result = true; 
       // Add if you want to know coordinates of the player 
       x = i; 
       y = j; 
      } 

    return result; 
} 

多次元配列では、行と列の両方の値を知る必要があります。 i = 0で始まり、1つのループを入れてtheBoard[i] [i]を探すと、行0 col 0を見て、次に1をiに追加します。i++、行1 col 1を見ています。スキップしていますほかのすべて。そのため、行と列の両方を反復処理するためには、ネストされたforループが必要です。

以下の例を見て...

0 1 2 3 4 5 
0 X X X X X X 
1 X X X X X X 
2 X X X X X X 
3 X X X X X X 
4 X X X X X X 
5 X X X X X X 

あなたはthePlayerのみのアレイの対角線のインデックスであるかどうかを確認したい場合は、ループのための単一を使用することができます。

私の意見では、このようなものにはforループを使用する方が簡単です。 whileループは本質的に異なる実装ですが、このような状況ではforループはよりクリーンで簡単に見えます。最終的には、どちらを実装するのが簡単かを決定するのはあなた次第です。

0
 for(char[] firstarray : theBoard){ 
      for(char ch : firstarray){ 
     boolean matches = (thePlayer == ch) ? true : false; 
     if(matches){ 
     System.out.println("matchFound");   
     }else{ 
     System.out.println("no match"); 
     } 

     } 
     } 

2次元配列を持つため、配列を2回ループする必要があります。通常のforループbtを使用すると、forループを使用してより簡単にループを使用できます。

0
public boolean diagonal(char[][] theBoard, char thePlayer) { 
     for(int i = 0; I < theBoard.length; i++) 
       for(int j = 0; j < theBoard[i].length; j++) 
         if (thePlayer == theBoard[i][j]) { 
           return = true; 
         } 
     return false; 
} 
関連する問題