2013-06-03 3 views
-1

좋아, 그래서이 프로그램은 단락에 출력 다섯 형용사와 명사를 입력 할 수 있습니다. 이 게임에는 특정 이름이 있습니다. 보통 아이의 잡지에서 찾아 볼 수 있습니다.하지만 그 이름은 지금 나를 도망칩니다. 전의. "메리는 (형용사) 말에서 뛰어 다녔다. 그리고 _ (명사)를 통해 날아 갔다. 지금은이 모든 더 레드 라인 또는 없기 때문에 잘 해결할 것이라고 생각했다클래스/배열을 출력하는 방법은 무엇입니까?

을 같은. 나는 누르면 그러나 후에" 사랑스러운 오류가 팝업 "버튼을 재생할 수 있습니다. 오류의

전 ... 나는 명사 텍스트 필드를 통해 배열에 추가 명사 수있는

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5 

'5'또는 수 (N)를. 당신이 궁금해하는 경우 GUI를 사용하고 있습니다. 미안 물리적 퀘스 티노가 이해가되지 않는다면, 어떻게 말할지는 확신 할 수 없었습니다.

명사와 형용사 모두를위한 클래스를 만들었습니다.

class noun { 
    String noun; 

    noun (String _noun) { 
     noun = _noun; 
    } 
} 

class adjective { 
    String adjective; 

    adjective (String _adjective) { 
     adjective = _adjective; 
    } 
} 

ArrayList <adjective> small = new ArrayList <adjective>(); //array for adjectives 
ArrayList <noun> office = new ArrayList <noun>(); //array for nouns 

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) { //stores info 

     String noun, adjective; 

     //Take inputted words 
     noun = nounField.getText(); 
     adjective = adjectiveField.getText(); 

     //Store values in array ADJECTIVE 
     adjective c = new adjective(adjective); 
     small.add(c); 

     //Store values in array NOUN 
     noun d = new noun(noun); 
     office.add(d); 

    } 

private void playButtonActionPerformed(java.awt.event.ActionEvent evt) { //play button 

     String temp = ""; 

     //Allows user to view information from array 
     for (int x=0; x<=office.size(); x++) { 
      temp = temp + " paragraph " + office.get(x).noun + "/n"; 
     } 
     paraTArea.setText(temp); //TextArea where paragraph with nouns etc are outputted 

도움이나 의견을 보내 주시면 감사하겠습니다. =)

+2

몇 가지 팁 : 1) 배열과는 아무런 관련이 없으며, 'Collection' 하위 클래스로 작업하고 있으며, 2) 코드 가독성을 향상시키는 데 유용한 변수 이름을 사용합니다. – SJuan76

+0

참고로이 게임을 알고있는 상표명은 "Mad Libs"입니다. – Nick

답변

4

인덱스가 0부터 시작하므로 for 루프의 상한값은 x <= office.size() - 1 또는 x < office.size()이어야합니다.

+0

아 ... 알았어, 와우, 고마워! 그건 내 멍청한 실수 였어. – user2407152

0

당신은 다음 중 하나에 루프 변경할 수 있습니다이 도움이된다면

for (int x=0; x<=office.size()-1; x++) //As suggested by mre 

또는

for (int x=0; x<office.size(); x++) 

을 참조하십시오.

+2

-1 두 번째 for-loop도'IndexOutOfBoundsException'을 발생시킵니다. – mre

+0

yes. 당신이 올바른지. 시정 해줘서 고마워. –

+1

@HarishKumar 그러면 고칠 수 있습니다. – ApproachingDarknessFish

관련 문제