2013-09-07 2 views
1

В моей игре-викторине я установил число раундов до 15. Неправильно ли ответ или правильная игра не заканчивается. При правильном ответе его показатель прироста в противном случае уменьшается. Моя игра викторины работает правильно, но я добавил таймер в том, чтобы, когда время следующего вопроса пришло и оценка уменьшилась. И после добавления метода таймера и декремента в методе timer() таймера. Моя игра работает только 8 или 9 раундов и заканчивается. А также оценка уменьшена на 150. Но в моем методе декрементScore() я устанавливаю декремент только на 50. Не добавляя этот метод в метод завершения таймера, его работа правильная. Мой код и лог-кошка ниже: - Спасибо заранее!Как решить эти ошибки logcat?

Код: -

public class QuestionActivity extends Activity implements OnClickListener{ 

    private Question currentQ; 
    private GamePlay currentGame; 

    @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.question); 
      processScreen(); 
    } 

    private void processScreen() 
    { 
       /** 
     * Configure current game and get question 
     */ 
     currentGame = ((CYKApplication)getApplication()).getCurrentGame(); 
     currentQ = currentGame.getNextQuestion(); 
     Button nextBtn1 = (Button) findViewById(R.id.answer1); 
     nextBtn1.setOnClickListener(this); 
     Button nextBtn2 = (Button) findViewById(R.id.answer2); 
     nextBtn2.setOnClickListener(this); 
     Button nextBtn3 = (Button) findViewById(R.id.answer3); 
     nextBtn3.setOnClickListener(this); 
     Button nextBtn4 = (Button) findViewById(R.id.answer4); 
     nextBtn4.setOnClickListener(this); 
     Button nextBtn5 = (Button) findViewById(R.id.answer5); 
     nextBtn5.setOnClickListener(this); 
     /** 
     * Update the question and answer options.. 
     */ 
     setQuestions(); 

    } 


    /** 
    * Method to set the text for the question and answers from the current games 
    * current question 
    */ 
    private void setQuestions() { 
     //set the question text from current question 
     String question = Utility.capitalise(currentQ.getQuestion()); 
     TextView qText = (TextView) findViewById(R.id.question); 
     qText.setText(question); 

     //set the available options 
     List<String> answers = currentQ.getQuestionOptions(); 
     TextView option1 = (TextView) findViewById(R.id.answer1); 
     option1.setText(Utility.capitalise(answers.get(0))); 

     TextView option2 = (TextView) findViewById(R.id.answer2); 
     option2.setText(Utility.capitalise(answers.get(1))); 

     TextView option3 = (TextView) findViewById(R.id.answer3); 
     option3.setText(Utility.capitalise(answers.get(2))); 

     TextView option4 = (TextView) findViewById(R.id.answer4); 
     option4.setText(Utility.capitalise(answers.get(3))); 

     int score = currentGame.getScore(); 
     String scr = String.valueOf(score); 
     TextView score1 = (TextView) findViewById(R.id.score); 
     score1.setText(scr); 

     new CountDownTimer(10000, 1000) { 

      public void onTick(long millisUntilFinished) { 
       TextView timers = (TextView) findViewById(R.id.timers); 
       timers.setText("Time: " + millisUntilFinished/1000); 
      } 

      public void onFinish() { 
       currentGame.decrementScore(); 
        processScreen(); 
            } 
     }.start(); 
     } 


    @Override 
    public void onClick(View arg0) { 
     //Log.d("Questions", "Moving to next question"); 
     if(arg0.getId()==R.id.answer5) 
     { 
     new AlertDialog.Builder(this) 
     .setMessage("Are you sure?") 
     .setCancelable(true) 
     .setPositiveButton("Yes", 
     new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, 
     int id) { 
       finish(); 
       } 
      }).setNegativeButton("No", null).show(); 

       } 

     else 
     { 
      if(!checkAnswer(arg0)) return; 

     /** 
     * check if end of game 
     */ 
     if (currentGame.isGameOver()){ 
      //Log.d("Questions", "End of game! lets add up the scores.."); 
      //Log.d("Questions", "Questions Correct: " + currentGame.getRight()); 
      //Log.d("Questions", "Questions Wrong: " + currentGame.getWrong()); 
      Intent i = new Intent(this, EndgameActivity.class); 
      startActivity(i); 
      finish(); 
     } 
     else{ 
      Intent i = new Intent(this, QuestionActivity.class); 
         finish(); 
         startActivity(i); 
     } 
     } 
     } 



    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    { 
     switch (keyCode) 
     { 
     case KeyEvent.KEYCODE_BACK : 
      return true; 
     } 

     return super.onKeyDown(keyCode, event); 
    } 


    /** 
    * Check if a checkbox has been selected, and if it 
    * has then check if its correct and update gamescore 
    */ 
    private boolean checkAnswer(View v) { 

     Button b=(Button) v; 
     String answer = b.getText().toString(); 

      //Log.d("Questions", "Valid Checkbox selection made - check if correct"); 
      if (currentQ.getAnswer().equalsIgnoreCase(answer)) 
      { 
       b.setBackgroundResource(R.drawable.answercolor); 
       //Log.d("Questions", "Correct Answer!"); 
       currentGame.incrementScore(); 
      } 
      else{ 
       b.setBackgroundResource(R.drawable.answercolorr); 
       //Log.d("Questions", "Incorrect Answer!"); 
       currentGame.decrementScore(); 
      } 
      return true; 
     } 

} 

класс, где оценка декремент и оцилиндрованное бревно прибавки кошка показывает некоторую ошибку в getNextQuestion() метод.

public class GamePlay { 

    private int numRounds; 
    private int difficulty; 
    private String playerName; 
    private int score; 
    private int round; 

    private List<Question> questions = new ArrayList<Question>(); 
    /** 
    * @return the right 
    */ 
    public int getScore() { 
     return score; 
    } 
    /** 
    * @param right the right to set 
    */ 
    public void setScore(int score) { 
     this.score = score; 
    } 

    /** 
    * @return the round 
    */ 
    public int getRound() { 
     return round; 
    } 
    /** 
    * @param round the round to set 
    */ 
    public void setRound(int round) { 
     this.round = round; 
    } 
    /** 
    * @param difficulty the difficulty to set 
    */ 
    public void setDifficulty(int difficulty) { 
     this.difficulty = difficulty; 
    } 
    /** 
    * @return the difficulty 
    */ 
    public int getDifficulty() { 
     return difficulty; 
    } 
    /** 
    * @param questions the questions to set 
    */ 
    public void setQuestions(List<Question> questions) { 
     this.questions = questions; 
    } 

    /** 
    * @param q the question to add 
    */ 
    public void addQuestions(Question q) { 
     this.questions.add(q); 
    } 

    /** 
    * @return the questions 
    */ 
    public List<Question> getQuestions() { 
     return questions; 
    } 


    public Question getNextQuestion(){ 

     //get the question 
     Question next = questions.get(this.getRound()); 
     //update the round number to the next round 
     this.setRound(this.getRound()+1); 
     return next; 
    } 

    /** 
    * method to increment the number of correct answers this game 
    */ 


    /** 
    * method to increment the number of incorrect answers this game 
    */ 
    public void incrementScore(){ 
     score=score+100; 
    } 

    public void decrementScore() 
    { 
     score=score-50; 
    } 
    /** 
    * @param numRounds the numRounds to set 
    */ 
    public void setNumRounds(int numRounds) { 
     this.numRounds = numRounds; 
    } 
    /** 
    * @return the numRounds 
    */ 
    public int getNumRounds() { 
     return numRounds; 
    } 

    /** 
    * method that checks if the game is over 
    * @return boolean 
    */ 
    public boolean isGameOver(){ 
     return (getRound() >= getNumRounds()); 
    } 


} 

журнал кошка: -

09-06 15:29:23.321: D/dalvikvm(3372): Debugger has detached; object registry had 1 entries 
09-06 15:30:00.081: D/gralloc_goldfish(3942): Emulator without GPU emulation detected. 
09-06 15:30:05.321: D/dalvikvm(3942): GC_FOR_ALLOC freed 39K, 7% free 2661K/2844K, paused 86ms, total 97ms 
09-06 15:30:05.371: I/dalvikvm-heap(3942): Grow heap (frag case) to 4.795MB for 2160016-byte allocation 
09-06 15:30:05.421: D/dalvikvm(3942): GC_FOR_ALLOC freed 1K, 4% free 4768K/4956K, paused 56ms, total 56ms 
09-06 15:30:05.541: D/dalvikvm(3942): GC_CONCURRENT freed 1K, 4% free 4767K/4956K, paused 8ms+35ms, total 118ms 
09-06 15:30:09.050: D/dalvikvm(3942): GC_FOR_ALLOC freed 16K, 3% free 5226K/5388K, paused 60ms, total 72ms 
09-06 15:30:09.080: I/dalvikvm-heap(3942): Grow heap (frag case) to 7.300MB for 2160016-byte allocation 
09-06 15:30:09.190: D/dalvikvm(3942): GC_CONCURRENT freed 242K, 6% free 7093K/7500K, paused 4ms+4ms, total 105ms 
09-06 15:30:10.140: I/Choreographer(3942): Skipped 768 frames! The application may be doing too much work on its main thread. 
09-06 15:30:12.360: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:13.364: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:16.191: I/Choreographer(3942): Skipped 53 frames! The application may be doing too much work on its main thread. 
09-06 15:30:17.191: I/Choreographer(3942): Skipped 46 frames! The application may be doing too much work on its main thread. 
09-06 15:30:20.225: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:21.251: I/Choreographer(3942): Skipped 45 frames! The application may be doing too much work on its main thread. 
09-06 15:30:22.951: I/Choreographer(3942): Skipped 62 frames! The application may be doing too much work on its main thread. 
09-06 15:30:23.934: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:26.042: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:27.050: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:28.821: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:31.370: I/Choreographer(3942): Skipped 30 frames! The application may be doing too much work on its main thread. 
09-06 15:30:31.830: I/Choreographer(3942): Skipped 48 frames! The application may be doing too much work on its main thread. 
09-06 15:30:32.447: I/Choreographer(3942): Skipped 45 frames! The application may be doing too much work on its main thread. 
09-06 15:30:33.474: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:34.501: I/Choreographer(3942): Skipped 51 frames! The application may be doing too much work on its main thread. 
09-06 15:30:35.981: I/Choreographer(3942): Skipped 50 frames! The application may be doing too much work on its main thread. 
09-06 15:30:36.991: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:38.008: I/Choreographer(3942): Skipped 45 frames! The application may be doing too much work on its main thread. 
09-06 15:30:40.082: I/Choreographer(3942): Skipped 43 frames! The application may be doing too much work on its main thread. 
09-06 15:30:40.181: D/AndroidRuntime(3942): Shutting down VM 
09-06 15:30:40.181: W/dalvikvm(3942): threadid=1: thread exiting with uncaught exception (group=0x40a71930) 
09-06 15:30:40.191: E/AndroidRuntime(3942): FATAL EXCEPTION: main 
09-06 15:30:40.191: E/AndroidRuntime(3942): java.lang.IndexOutOfBoundsException: Invalid index 15, size is 15 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at java.util.ArrayList.get(ArrayList.java:304) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at com.abc.cyk.quiz.GamePlay.getNextQuestion(GamePlay.java:100) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at com.abc.cyk.QuestionActivity.processScreen(QuestionActivity.java:42) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at com.abc.cyk.QuestionActivity.access$0(QuestionActivity.java:36) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at com.abc.cyk.QuestionActivity$1.onFinish(QuestionActivity.java:98) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at android.os.Handler.dispatchMessage(Handler.java:99) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at android.os.Looper.loop(Looper.java:137) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at android.app.ActivityThread.main(ActivityThread.java:5041) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at java.lang.reflect.Method.invoke(Method.java:511) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
09-06 15:30:40.191: E/AndroidRuntime(3942):  at dalvik.system.NativeStart.main(Native Method) 
09-06 15:30:44.592: E/Trace(3971): error opening trace file: No such file or directory (2) 
09-06 15:30:44.691: D/dalvikvm(3971): GC_FOR_ALLOC freed 36K, 7% free 2413K/2592K, paused 27ms, total 29ms 
09-06 15:30:44.711: I/dalvikvm-heap(3971): Grow heap (frag case) to 4.553MB for 2160016-byte allocation 
09-06 15:30:44.821: D/dalvikvm(3971): GC_FOR_ALLOC freed 1K, 4% free 4521K/4704K, paused 107ms, total 107ms 
09-06 15:30:44.871: D/dalvikvm(3971): GC_CONCURRENT freed <1K, 4% free 4521K/4704K, paused 4ms+3ms, total 50ms 
09-06 15:30:45.341: D/gralloc_goldfish(3971): Emulator without GPU emulation detected. 
09-06 15:30:47.540: I/Choreographer(3971): Skipped 64 frames! The application may be doing too much work on its main thread. 

я обнаружил, где ошибки им мой код. метод finish() в методе таймера обратного отсчета останавливает завершение цикла и метода декремента уменьшает оценку на каждом раунде, а не уменьшает его в разы. Может кто-то знает, как его решить. Пожалуйста, помогите мне.

+0

'java.lang.IndexOutOfBoundsException: недействительный индекс 15, размер 15 09-06 15: 30: 40,191: Е/AndroidRuntime (3942): в com.abc.cyk.quiz.GamePlay.getNextQuestion (GamePlay.java : 100) 'Вы пытались получить 16-й вопрос, когда в массиве вопросов было только 15 вопросов. – Simon

+0

Выбросив исключение IndexOutOfBounds с одним из ваших arraylists, я не смог полностью выполнить ваш код из-за того, что был на телефоне в формате, но я думаю, что здесь вы получите следующий вопрос. Вы плюс 1 к раунду, который если вы сделаете это в начале и в конце, вы перейдете выше своего индекса, потому что начинаете с 1, а не 0 ... Извините, если мои комментарии запутывают –

+0

извините за 15 раундов. По ошибке я написал 20 в своем объяснении в первую очередь. Его работа подходит только 7 или 8 раундов. –

ответ

-1

Ошибки, показанные на этом изображении, являются ошибками компиляции. Это не то, что он хочет. Ему нужны ошибки во время выполнения. Он делает это правильно, однако он, кажется, не вставляет весь свой вывод журнала, так как ни одна из строк, которые он опубликовал, не является строкой ошибок.

EDIT: Вернее, это системные ошибки, которые разработчик может игнорировать при автоматическом управлении системой. То, что вам нужно наблюдать, - это нечеткие исключения, такие как NullPointerException или IllegalStateException и т. Д. Это ошибки на уровне приложений и те, которые вам нужно исправить.

+0

Ошибки с com.abc.cyk - ошибки времени выполнения, я думаю. Потому что его красный цвет в журнале cat. –

+1

Дайте мне разумный ответ. –

Смежные вопросы