java - (Android Studio) 我的 Tic-Tac-Toe 游戏由于 (java.lang.IllegalStateException : Could not execute method for android:onClick) error

标签 java android

我是 Android 新手。我在 Android Studio 中创建了一个简单的 Tic-Tac-Toe 游戏。它有一个网格和一个状态栏,可以告诉轮到谁以及谁赢了。我还添加了重置游戏的方法。游戏运行良好,但每当玩家获胜时,游戏就会崩溃(TicTacToeme 已停止)。

我也尝试过初始化一些变量,但这对我不起作用。

这是我的完整 MainActivity.java 代码:

package com.jashanubhi.tictactoeme;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int activePlayer = 0;
    boolean gameActive = true;
    int[] gameState = {2,2,2,2,2,2,2,2,2};
    int[][] winningPositions = {{0,1,2}, {3,4,5}, {6,7,8},
                                {0,4,8}, {2,4,6},
                                {0,3,6}, {1,4,7}, {2,5,8}};

    public void playerTap(View view) {
        ImageView img;
        img = (ImageView) view;
        int tappedImage;
        tappedImage = Integer.parseInt(img.getTag().toString());
        TextView status;
        status = findViewById(R.id.status);
        if (gameState[tappedImage] == 2 && gameActive) {
            gameState[tappedImage] = activePlayer;
            img.setTranslationY(-1000f);
            if (activePlayer == 0) {
                img.setImageResource(R.drawable.x);
                activePlayer = 1;
                status.setText("O's Turn - Tap to Play");
            } else {
                img.setImageResource(R.drawable.o);
                activePlayer = 0;
                status.setText("X's Turn - Tap to Play");
            }
            img.animate().translationYBy(1000f).setDuration(300);
        }
        for (int[] winningPosition : winningPositions) {
            if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]]
                    && gameState[winningPosition[0]] != 2) {
                if (winningPosition[0] == 0) {
                    status.setText("X has won");
                }
                if (winningPosition[0] == 1) {
                    status.setText("O has won");
                }
                gameActive = false;
            }
        }
        if(!gameActive){
            gameReset(view);
        }
    }

    public void gameReset(View view){
        activePlayer = 0;
        gameActive = true;
        for(int i = 0; i <= gameState.length; i++){
            gameState[i] = 2;
        }
        ((ImageView)findViewById(R.id.imageView0)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView1)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView2)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView3)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView4)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView5)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView6)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView7)).setImageResource(0);
        ((ImageView)findViewById(R.id.imageView8)).setImageResource(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}


这是我的 Logcat(仅错误):

2020-03-29 15:15:36.635 6517-6517/com.jashanubhi.tictactoeme E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.jashanubhi.tictactoeme, PID: 6517
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:5610)
        at android.view.View$PerformClick.run(View.java:22265)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:5610) 
        at android.view.View$PerformClick.run(View.java:22265) 
        at android.os.Handler.handleCallback(Handler.java:751) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6077) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
     Caused by: java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
        at com.jashanubhi.tictactoeme.MainActivity.gameReset(MainActivity.java:61)
        at com.jashanubhi.tictactoeme.MainActivity.playerTap(MainActivity.java:53)
        at java.lang.reflect.Method.invoke(Native Method) 
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
        at android.view.View.performClick(View.java:5610) 
        at android.view.View$PerformClick.run(View.java:22265) 
        at android.os.Handler.handleCallback(Handler.java:751) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6077) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)


这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="@string/title"
        android:textSize="38dp"
        android:textStyle="bold"
        app:fontFamily="sans-serif-light"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="398dp"
        android:layout_height="398dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@drawable/grid" />

    <TextView
        android:id="@+id/status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="X's Turn - Tap to Play"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <LinearLayout
        android:layout_width="398dp"
        android:layout_height="398dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/textView">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageView0"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="0" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="1" />

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="2" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageView3"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="3" />

            <ImageView
                android:id="@+id/imageView4"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="4" />

            <ImageView
                android:id="@+id/imageView5"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="5" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/imageView6"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="6" />

            <ImageView
                android:id="@+id/imageView7"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="7" />

            <ImageView
                android:id="@+id/imageView8"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="playerTap"
                android:padding="23sp"
                android:tag="8" />
        </LinearLayout>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

最佳答案

您的问题在 gameReset您获得的功能 java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
因为里面有循环。
你正在做for(int i = 0; i <= gameState.length; i++)但循环停止的术语是 i<=gameState.length而不是i<gameState.length
这会导致您访问数组长度 pos 中的数组,例如,如果数组长度为 5 并且您想要获取第 5 个,这是您应该在数组中访问的最大位置 arr[4]但您正在尝试访问arr[5]它不在数组中,因此您得到 java.lang.ArrayIndexOutOfBoundsException .

关于java - (Android Studio) 我的 Tic-Tac-Toe 游戏由于 (java.lang.IllegalStateException : Could not execute method for android:onClick) error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60913110/

相关文章:

java - 程序在 JFrame 高度最大化时不重新绘制

java - 选择 Java 7 JRE 通过 Cloud Tools for Eclipse 运行 App Engine Dev Server

android - 在 Fragment 中使用 Toast

android - Google Play 应用内评论 API : How long is the ReviewInfo object valid?

安卓 : MultiChoiceModeListener not invoked inside ListFragment

java - 如何删除存储在 Java FileOutputStream 上的单个对象

java - @Transactional 的动态事务隔离级别

java - 如何使用java重命名linux目录中的所有文件?

java - 安卓房间: error: setValue(T) has protected access in LiveData

android - 如何自动化 android 的升级测试