2011-11-01 4 views
2

사람이 질문을 한 다음 답변을해야하는이 퀴즈 프로그램을 만들려고 노력 중이므로 두 사람을위한 게임이며 계속 진행됩니다. 모든 질문과 게임이 끝납니다.안드로이드/자바 : arraylist가 비어 있는지 확인한 다음 다른 활동을 시작하십시오.

내가 지금까지 만들었던 것은 배열 (strings.xml 파일의 배열)을 arraylist로로드하고 arraylist.size로 임의의 ID를 취한 다음 문자열 (질문) 그러면 임의의 ID를 삭제하고 새 ID를 가져옵니다. 필자가 ArrayList의 모든 아이디의를 통해 프로그램이 충돌을 실행할 때

는하지만, 내 코드는 다음과 같습니다

public void gameCode() 
{ 
    setContentView(R.layout.game); 
    if (mList == null) 
{ 
    String[] mQuestions = getResources().getStringArray(R.array.mQuestions); 
    mList = new ArrayList(); 
    Collections.addAll(mList, mQuestions); 
} 
    else if (mList.isEmpty()) 
{ 
    m = (TextView)findViewById(R.id.textView1); 
     m.setText("You've run out of questions!"); 
} 
if (wList == null) 
{ 
    String[] wQuestions = getResources().getStringArray(R.array.wQuestions); 
    wList = new ArrayList(); 
    Collections.addAll(wList, wQuestions); 
} 
else if (wList.isEmpty()) 
{ 
    w = (TextView)findViewById(R.id.textView1); 
      w.setText("You've run out of questions!"); 
} 

    //Takes a random ID from the arraylist 
    int rndm = generator.nextInt(mList.size()); 
    int rndw = generator.nextInt(wList.size()); 


    //Sets the Strings to a random number from one of the array lists 
    String qMan = (String) mList.get(rndm); 
    String qWoman = (String) wList.get(rndw); 
    if(i == 0) 
     { 
      //Defines that w is textView1 with the value of qWoman 
      w = (TextView)findViewById(R.id.textView1); 
      w.setText(qWoman); 
      wList.remove(rndw); 
      i = 1; 
      final Button buttonNext = (Button) findViewById(R.id.buttonNext); 
      buttonNext.setOnClickListener(new View.OnClickListener() 
      { 
       public void onClick(View v) 
       { 
        gameCode(); 
       } 
      }); 
     } 
    else 
     { 

      m = (TextView)findViewById(R.id.textView1); 
      m.setText(qMan); 
      mList.remove(rndm); 
      i = 0; 
      final Button buttonNext = (Button) findViewById(R.id.buttonNext); 
      buttonNext.setOnClickListener(new View.OnClickListener() 
      { 
       public void onClick(View v) 
       { 
        gameCode(); 
       } 
      }); 
     } 

} 

}

이 있습니다 : http://pastebin.com/MaEj49BL

중요한 부분은 이것이다 pastebin에서 소스 코드의 주석. 지금은 단지 당신은이 개 배열이 비어 있는지 여부를 확인하고

답변

3

널 안전

+0

프로그램이 잘 실행되고 있습니다. 충돌 지점은 arraylist의 항목이 부족할 때입니다. – psalomonsen

+0

오른쪽. 따라서 배열 목록에 더 이상 항목이 없으면 무작위로 질문을 선택하고 질문 텍스트를보기로 설정하는 코드를 실행하고있는 것입니다. 예를 들어, wList에 0 개의 항목이 있고 i == 0이라고 가정하면 난수 생성기는 0을 반환하고 wList.get (rdmn)을 시도하면 폭파합니다. – Chris

+0

고마워 .. 무작위 생성기 등 전에 if 문을 추가하고 (mList.size()> 0 && wList.size()> 0) charm'code처럼 작동했습니다. – psalomonsen

1

사용 CollectionUtils.isEmpty() "당신은 질문이 부족했습니다"로 텍스트를 변경해야 하지만 나머지 로직을 단락시키지 않아도됩니다.

mList 및 wList가 비어 있으면 메소드의 나머지 부분을 건너 뛰거나 시도하기 전에 최소한 mList.size() > 0and wList.size()>0을 확인해야합니다. 각 배열에서 다음 무작위 질문을 얻을 수 있습니다.

+0

else if 문에서 사용해야합니까? – psalomonsen

관련 문제