java - Int 类型和 String 类型不兼容

标签 java string int incompatibility

嘿,我正在完成这个井字游戏项目,但我的 checkWin 方法中的棋盘类中有一个错误,其中 Winner = board[0][i]; Int 和 String 会出现不兼容错误。我已经使用 Integer.toString() 命令在我的另一条板上修复了此问题,但它对此不起作用。有任何想法吗?这是 checkWin 方法的代码。

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; 
}



}   

最佳答案

winner = board[0][i];

winner 是 int 基元类型,board 是多维字符串数组。

您正在尝试为 int 分配一个字符串,因此Int 和 String 会出现不兼容的错误

String[][] board;  

其索引处有字符串,当您尝试访问board[0][i]时,您正在检索字符串。

如果您的棋盘数组包含数字的字符串表示形式,例如

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

然后使用 Integer.parseInt() ,它将 String 作为参数并返回一个 Integer。

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

但请注意,如果传递给 parseInt 的字符串不是字符串的有效整数表示,它将抛出 NumberFormatException

关于java - Int 类型和 String 类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13242441/

相关文章:

c - 如何根据 C 中的多个定界符分隔字符串?

java - 为什么 char[] 优于 String 作为密码?

c - 是否可以在没有 for 循环的情况下执行“离散”几何和?

text - 如何声明文本字段只能包含整数?

java - Ubuntu 没有 Java?

java - 我正在尝试使用 java 的声音 API 获取 wav 文件的音量级别,但无法弄清楚

java - JLabel 点击效果如 "Mac OS"系统偏好设置的图标

javascript - 从任意正则表达式创建字符串模板?

java - 将字符串转换为整数

google 注册中的 java.lang.NullPointerException 抛出 null