2017-12-07 17 views
-2

안녕하세요 저는 여러 퀴즈 앱을 만들고 싶지만 앱이 마지막 질문 일 때 갑자기 중단됩니다. 마지막 점수를 계산 한 후 대화 상자에 표시하고 main으로 돌아가고 싶습니다.ArrayIndexOufOfBoundsException

class QuestionsBD { 

private String bdquestions[]= { 
     "Componenta de date dintr-un SBD poate contine: ", 
     "In arhitectura unui SBD pe niveluri, viziunea programatorului corespunde: ", 
     "Arhitectura pe componente a unui sistem de baze de date contine:"}; 

private String bdChoices[][]={ 
     {"Sistemul de operare","Sistemul de coduri","Dictionarul distribuit","Fisierele anexe"}, 
     {"Nivelul fizic","Nivelul SO","Nivelul logic","Nivelul SGBD"}, 
     {"Datele","Fisierele","Software-ul de comunicatie","Programe de comunicatie"} 
}; 

private String bdCorrectAns[]={"Fisierele anexe", "Nivelul logic","Datele"}; 


public String getQuestion(int a) 
{ 
    String question= bdquestions[a]; 
    return question; 
} 

public String getChoice0(int a) 
{ 
    String choice0=bdChoices[a][0]; 
    return choice0; 
} 

public String getChoice1(int a) 
{ 
    String choice1=bdChoices[a][1]; 
    return choice1; 
} 

public String getChoice2(int a) 
{ 
    String choice2=bdChoices[a][2]; 
    return choice2; 
} 

public String getChoice3(int a) 
{ 
    String choice3=bdChoices[a][3]; 
    return choice3; 
} 



public String getCorrectAnswer(int a) 
{ 
    String answer=bdCorrectAns[a]; 
    return answer; 
} 

public int getNrQuestions() 
{ 
    int nrquestions=bdquestions.length; 
    return nrquestions; 
    } 
} 

그리고이 질문에 표시되는 활동입니다 :

오류

12-07 22:38:17.997 29516-29516/com.example.ancaalexandra.proiectandroidd E/AndroidRuntime: FATAL EXCEPTION: main 
                           Process: com.example.ancaalexandra.proiectandroidd, PID: 29516 
                           java.lang.ArrayIndexOutOfBoundsException: length=3; index=3 
                            at com.example.ancaalexandra.proiectandroidd.QuestionsBD.getQuestion(QuestionsBD.java:27) 
                            at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.updateQuestion(BazeDeDate1Activity.java:150) 
                            at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity.access$400(BazeDeDate1Activity.java:19) 
                            at com.example.ancaalexandra.proiectandroidd.BazeDeDate1Activity$1.onClick(BazeDeDate1Activity.java:78) 
                            at android.view.View.performClick(View.java:6261) 
                            at android.widget.TextView.performClick(TextView.java:11185) 
                            at android.view.View$PerformClick.run(View.java:23752) 
                            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:6776) 
                            at java.lang.reflect.Method.invoke(Native Method) 
                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408) 

내가 질문과 답을 작성하는 곳, QuestionsBD 클래스입니다

public class BazeDeDate1Activity extends AppCompatActivity implements View.OnClickListener { 

    private QuestionsBD questBd = new QuestionsBD(); 

    private TextView scoreTW; 
    private TextView questionsTW; 
    private Button choice0; 
    private Button choice1; 
    private Button choice2; 
    private Button choice3; 
    private Button choiceQuit; 
    private ImageView numberPhoto; 

    private String answer; 
    private int scoreInit = 0; 
    private int questionNumber = 0; 
    private String quit = "quit"; 

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

     View v = findViewById(R.id.buttonBD1quit); 
     v.setOnClickListener(this); 

     /*AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage("Scor final: " + scoreInit); 
     builder.setTitle("Felicitari!!"); 

     builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int idok) { 

      } 
     }); 

     AlertDialog dialog = builder.create(); 
*/ 
     scoreTW = (TextView) findViewById(R.id.textViewScorObtinut); 
     questionsTW = (TextView) findViewById(R.id.textViewIntrebare1BD); 
     choice0 = (Button) findViewById(R.id.buttonBD1r1); 
     choice1 = (Button) findViewById(R.id.buttonBD1r2); 
     choice2 = (Button) findViewById(R.id.buttonBD1r3); 
     choice3 = (Button) findViewById(R.id.buttonBD1r4); 
     choiceQuit = (Button) findViewById(R.id.buttonBD1quit); 
     numberPhoto = (ImageView) findViewById(R.id.imageViewONE); 

     //updateQuestion(); 

     choice0.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       if (choice0.getText() == answer) { 
        scoreInit = scoreInit + 1; 
        updateScore(scoreInit); 
        Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show(); 

        updateQuestion(); 


       } else { 
        Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show(); 

         updateQuestion(); 


       } 
      } 
     }); 

     choice1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       if (choice1.getText() == answer) { 
        scoreInit = scoreInit + 1; 
        updateScore(scoreInit); 
        Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show(); 
         updateQuestion(); 

       } else { 
        Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show(); 
        updateQuestion(); 
       } 

      } 
     }); 

     choice2.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       if (choice2.getText() == answer) { 
        scoreInit = scoreInit + 1; 
        updateScore(scoreInit); 
        Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show(); 


       } else { 
        Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show(); 

       } 
      } 
     }); 

     choice3.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       if (choice3.getText() == answer) { 
        scoreInit = scoreInit + 1; 
        updateScore(scoreInit); 
        Toast.makeText(BazeDeDate1Activity.this, "Correct", Toast.LENGTH_LONG).show(); 


       } else { 
        Toast.makeText(BazeDeDate1Activity.this, "Wrong", Toast.LENGTH_LONG).show(); 

       } 
      } 
     }); 


    } 



    private void updateQuestion() 
    { 
     questionsTW.setText(questBd.getQuestion(questionNumber)); 
     choice0.setText(questBd.getChoice0(questionNumber)); 
     choice1.setText(questBd.getChoice1(questionNumber)); 
     choice2.setText(questBd.getChoice2(questionNumber)); 

     answer=questBd.getCorrectAnswer(questionNumber); 
     questionNumber++; 
    } 

    private void updateScore(int point) 
    { 
     scoreTW.setText(""+scoreInit); 
    } 



    @Override 
    public void onClick(View v) { 
     if(v.getId()==R.id.buttonBD1quit) 
     { 
      Intent intent=new Intent(this,BeginActivity.class); 
      this.startActivity(intent); 
     } 
    } 
} 
+1

java.lang.ArrayIndexOutOfBoundsException : length = 3; index = 3'이 오류에 대해 수행 한 연구와 정확히 무엇이 당신을 혼란스럽게하는지 설명하십시오. – csmckelvey

답변

0

마지막 질문을 끝내면 코드가 계속 실행되어 네 번째 questio로 업데이트하려고합니다. n, 또는 bdquestions [] 배열의 인덱스 3. 당신은 다음과 같이 마지막 질문 후 뭔가를 중지 확인하기 위해 검사를 추가해야합니다 : 3이 bdquestions 배열의 하드 크기가 때 3의 값으로 String getQuestion(int a)를 호출

private void updateQuestion() 
{ 
    if (questionNumber < questBd.getNrQuestions()) { 
     questionsTW.setText(questBd.getQuestion(questionNumber)); 
     choice0.setText(questBd.getChoice0(questionNumber)); 
     choice1.setText(questBd.getChoice1(questionNumber)); 
     choice2.setText(questBd.getChoice2(questionNumber)); 

     answer=questBd.getCorrectAnswer(questionNumber); 
     questionNumber++; 
    } 
} 
0

. 이것이 해결 될 수있는 여러 가지 방법이 있지만 근본적인 문제는 하드 코드 된 데이터 세트와 하드 코딩 된 데이터가있을 것으로 기대되는 코드베이스를 사용하는 응용 프로그램 디자인입니다. 숫자가 < 3인지 확인할 수 있지만 문제를 해결하는 대신 문제를 숨길 수 있습니다. 당신이 for 루프와 가능한 답변을 반복 직접 (안전하게)에 액세스 할 수 있습니다, 거기에서

public class Question { 

    public Question(String question, int answerIndex, String... answers) { 
     this.question = question; 
     this.correctAnswerIndex = answerIndex; 
     this.answers.addAll(Arrays.asList(answers)); 
    } 

    private String question; 

    private List<String> answers = new ArrayList<>(); 

    private int correctAnswerIndex = 0; 

    private String getQuestion() { 
     return question; 
    } 

    private List<String> getAnswers() { 
     return answers; 
    } 

    private String getCorrectAnswer() { 
     if(answers.size() > correctAnswerIndex) { 
      return answers.get(correctAnswerIndex); 
     } 
     return null; 
    } 
} 

점점 :

우선 들어

, 당신은 당신의 질문/답변에 대한 데이터 형식을 가지고 있어야 비 하드 코드 방식의 응답 등이 포함됩니다. 충돌 또는 정의되지 않은 동작으로부터 보호되는 응용 프로그램을 만드는 가장 큰 부분은 오류 상태를 만들기 어렵도록 신중하게 설계하는 것입니다.