Android Studio开发Quiz应用启动崩溃求助(数组越界异常)
Hey there! I totally get how frustrating it is when your app crashes right at launch—especially when you’re swamped with student work. Let’s break down what’s going wrong and fix it step by step.
The Root Cause
Your crash log points straight to a java.lang.ArrayIndexOutOfBoundsException in Question.getChoice4(Question.java:38). Here’s why this happens:
- In your
Questionclass, themChoicesarray only has 3 options per question (each sub-array has length 3, with valid indexes 0, 1, 2). - But your
getChoice4()method tries to access index 3 of these sub-arrays, which doesn’t exist. - When your
MainActivitycallsupdateQuestion()on launch, it tries to set text for thechoice4button using this broken method, triggering an immediate crash.
Solution 1: Add a 4th Option for Each Question
If you want to keep the 4-choice button layout, update your Question.java to include a 4th option in every sub-array of mChoices:
package ict402.germio.examplequiz; public class Question { public String mQuestions [] = { "Complete the Statement Pogi si _________.", "What is the our Company Name?", "What is the Filipino word for Verb?", "Neil armstrong stepping onto the _________." }; // Updated: Added 4th option to each sub-array private String mChoices [][] = { {"Neil", "Ranier", "Jason", "John"}, {"Google Inc.", "innoTech", "STI", "Microsoft"}, {"Panguri", "Pandesal", "Panaguri", "Pandiwa"}, {"Jupiter", "Moon", "Tae ng Kalabaw", "Mars"} }; private String mCorrectAnswers[] = {"Neil", "innoTech", "Pandiwa", "Moon"}; public String getQuestion(int a) { return mQuestions[a]; } public String getChoice1(int a) { return mChoices[a][0]; } public String getChoice2(int a) { return mChoices[a][1]; } public String getChoice3(int a) { return mChoices[a][2]; } public String getChoice4(int a) { return mChoices[a][3]; // Now valid, since each sub-array has 4 elements } public String getCorrectAnswer(int a) { return mCorrectAnswers[a]; } }
Solution 2: Remove the 4th Choice Button
If you only need 3 options per question, adjust your code to remove all references to the 4th choice:
Step 1: Update Question.java
Delete the getChoice4() method entirely—you won’t need it anymore.
Step 2: Update MainActivity.java
Remove all code related to choice4:
package ict402.germio.examplequiz; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Random; public class MainActivity extends AppCompatActivity { Button choice1, choice2, choice3, quit; // Removed choice4 TextView score, question; private Question mQuestions = new Question(); private String mAnswer; private int mScore = 0; private int mQuestionsLength = mQuestions.mQuestions.length; Random r; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); r = new Random(); // Buttons - Removed choice4 initialization choice1 = findViewById(R.id.choice1); choice2 = findViewById(R.id.choice2); choice3 = findViewById(R.id.choice3); quit = findViewById(R.id.quit); //TextViews score = findViewById(R.id.score); question = findViewById(R.id.question); score.setText("Score: " + mScore); updateQuestion(r.nextInt(mQuestionsLength)); choice1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (choice1.getText().toString().equals(mAnswer)) { mScore++; score.setText("Score: " + mScore); updateQuestion(r.nextInt(mQuestionsLength)); } else { gameOver(); } } }); choice2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (choice2.getText().toString().equals(mAnswer)) { mScore++; score.setText("Score: " + mScore); updateQuestion(r.nextInt(mQuestionsLength)); } else { gameOver(); } } }); choice3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (choice3.getText().toString().equals(mAnswer)) { mScore++; score.setText("Score: " + mScore); updateQuestion(r.nextInt(mQuestionsLength)); } else { gameOver(); } } }); quit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } private void updateQuestion(int num) { question.setText(mQuestions.getQuestion(num)); choice1.setText(mQuestions.getChoice1(num)); choice2.setText(mQuestions.getChoice2(num)); choice3.setText(mQuestions.getChoice3(num)); // Removed choice4.setText(...) line mAnswer = mQuestions.getCorrectAnswer(num); } private void gameOver() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this); alertDialogBuilder .setMessage("Game Over! Your Score is " + mScore + "pts.") .setCancelable(false) .setPositiveButton("NEW GAME", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(new Intent(getApplicationContext(), MainActivity.class)); } }) .setNegativeButton("EXIT", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } }
Bonus Fix: Correct Answer Comparison
I noticed another issue that might break your score tracking later: you’re using == to compare text strings. In Java, == checks for reference equality, not content equality. I’ve updated the click listeners in the code above to use equals() instead—this ensures your app correctly identifies when a user picks the right answer.
内容的提问来源于stack exchange,提问作者Neil

