2012-11-06 151 views
1

嘿即時完成這個tic tac腳趾項目,我在我的棋盤類中有一個錯誤,在我的checkWin方法中,贏家= board [0] [i];作爲Int和String的不兼容錯誤出現。我已經通過使用Integer.toString()命令解決了這個問題,但它不適用於此。有任何想法嗎?以下是checkWin方法的代碼。類型Int和字符串不兼容

public boolean checkWin() 
{ 
    { 
     int i; // i = column 
     int j; // j = row 
     int count; 
     int winner; 

      winner = empty; // nobody has won yet 

// Check all rows to see if same player has occupied every square. 

     for (j = 0; j < boardSize; j ++) 
{ 
     count = 0; 
    if (board[j][0] != Integer.toString(empty)) 

    for (i = 0; i < boardSize; i ++) 
    if (board[j][0] == board[j][i]) 
    count ++; 
    if (count == boardSize) 
    winner = (board[j][0]); 
} 

// Check all columns to see if same player has occupied every square. 

    for (i = 0; i < boardSize; i ++) 
{ 
    count = 0; 
    if (board[0][i] != Integer.toString(empty)) 
    for (j = 0; j < boardSize; j ++) 
    if (board[0][i] == board[j][i]) 
    count ++; 
    if (count == boardSize) 
    winner = board[0][i]; 
} 

// Check diagonal from top-left to bottom-right. 

    count = 0; 
    if (board[0][0] != Integer.toString(empty)) 
    for (j = 0; j < boardSize; j ++) 
    if (board[0][0] == board[j][j]) 
    count ++; 
if (count == boardSize) 
winner = board[0][0]; 

// Check diagonal from top-right to bottom-left. 

count = 0; 
if (board[0][boardSize-1] != Integer.toString(empty)) 
for (j = 0; j < boardSize; j ++) 
if (board[0][boardSize-1] == board[j][boardSize-j-1]) 
count ++; 
if (count == boardSize) 
winner = board[0][boardSize-1]; 

// Did we find a winner? 

if (winner != empty) 
{ 
if (winner == Xstr) 

System.out.println("\nCongratulations! P1 You win!"); 
else if (winner == Ostr) 

System.out.println("\nCongratulations! P2 You win!"); 
else 


return true; 
} 



} 
+0

你的董事會是什麼[] []類型? – PermGenError

+0

在班上講清楚,板子是私人String [] []板子; – user1801642

+3

使用['Integer.valueOf(String)'](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#valueOf(java.lang.String))將您的字符串值轉換爲整數。 – toniedzwiedz

回答

0
winner = board[0][i]; 

winner是一個int原始類型並board是多維字符串數組。

你想分配一個字符串一個int因此不兼容錯誤int和string

String[][] board; 

在其索引處具有字符串,當您嘗試訪問board[0][i]時,您正在檢索字符串。

如果主板數組包含像

 boards= {{"1"},{"2"}}; 

號碼的字符串表示,然後使用的Integer.parseInt(),接受字符串作爲參數並返回一個整數。

winner = Integer.parseInt(board[0][i]); 

,但請不要忘記,如果傳遞給parseInt函數的字符串不是一個字符串的有效整數represetation它會拋出NumberFormatException的

相關問題