CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Question ArrayIndexOutOfBoundsException?

    So I'm trying to make my program so it can have different arrangements of phrases. I think I've got the right idea but it's not working out too well. If you can, please help!

    Code:
    //Phrasebot is property of shakenearth.com
    //Code by Thomas Lisankie
    //You may not use any of this code
    //you may not distribute this program either
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.Box;
    import java.io.*;
    import java.net.*;
    public class Phrasebot implements ActionListener {
    	
    	JTextArea midgui;
    	JButton phrasemaker;
    	Box boxleft;
    	
    	JTextField nounbox1;
    	JTextField nounbox2;
    	JTextField nounbox3;
    	
    	JTextField adjbox1;
    	JTextField adjbox2;
    	JTextField adjbox3;
    	
    	JTextField verbbox1;
    	JTextField verbbox2;
    	JTextField verbbox3;
    	
    	ArrayList<String> nouns = new ArrayList<String>();
    	ArrayList<String> adjectives = new ArrayList<String>();
    	ArrayList<String> verbs = new ArrayList<String>();
    	
    	String[] nounarray = nouns.toArray(new String[nouns.size()]);
    	String[] adjarray = adjectives.toArray(new String[adjectives.size()]);
    	String[] verbarray = verbs.toArray(new String[verbs.size()]);
    	
    	int countnoun = nounarray.length;
    	int countadj = adjarray.length;
    	int countverb = verbarray.length;
    	
    	int ran1 = (int) (Math.random() * countverb);
    	int ran2 = (int) (Math.random() * countadj);
    	int ran3 = (int) (Math.random() * countnoun);
    	
    	 String funny1 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny2 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	 String funny3 = adjarray [ran2]+ " " +  nounarray [ran3]+" " + verbarray [ran1]+" ";
    	String a;
    	
    	JTextField savefield;
    	JButton save;
    	
    	
    	
    	String p;
    	
    	
    public static void main(String[] args){
    try{
    	
    	Phrasebot bot = new Phrasebot();
    bot.go();
    }catch(Error Ex){
    	Ex.printStackTrace();
    }
    }
    public void go() {
    	
    	
    	JPanel pcenter = new JPanel();
    	JFrame frame = new JFrame("Phrasebot");//makes a new JFrame called "Phrasebot"
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//sets the default close operation to EXIT_ON_CLOSE
    	boxleft = new Box(BoxLayout.Y_AXIS);
    	
    	
    	JPanel bigpanel = new JPanel();//makes a new JPanel called bigpanel
    	bigpanel.setLayout(new BoxLayout(bigpanel,BoxLayout.Y_AXIS));//sets bigpanel's default layout to BoxLayout
    	JPanel spacer = new JPanel();//makes a new JPanel called spacer
    	spacer.setLayout(new BoxLayout(spacer, BoxLayout.Y_AXIS));//sets spacer's layout to BoxLayout
    	JLabel label = new JLabel(" ");//makes a new JLabel
    	spacer.add(label);//adds label to spacer
    	bigpanel.add(spacer);//adds spacer to bigpanel
    	JPanel peast = new JPanel();//makes a new panel called peast
    	bigpanel.add(peast);//bigpanel adds peast
    	peast.setLayout(new  BoxLayout(peast,BoxLayout.Y_AXIS));//sets peast's layout to boxlayout
    	JButton morenoun = new JButton("Add a Noun");//makes a new button called more noun with the text "More Nouns"
    	morenoun.addActionListener(new morenounListener());//morenoun adds an actionlistener which is a morenounlistener()
    	peast.add(morenoun);//peast adds morenoun
    	JButton clearnoun = new JButton("Clear Nouns");//makes a new button called clearnoun with the text "Clear Nouns"
    	clearnoun.addActionListener(new clearnounListener());//clearnoun adds an actionlistener which is a clearnounlistener()
    	peast.add(clearnoun);//peast adds clearnoun
    	JLabel spacer2 = new JLabel(" ");//makes a new label called spacer2
    	peast.add(spacer2);//peast adds spacer2
    	JButton moreadj = new JButton("Add an Adjective");//makes a new button called moreadj with the text "More Adjectives"
    	moreadj.addActionListener(new moreadjListener());//moreadj adds an actionlistener which is a moreadjlistener()
    	peast.add(moreadj);//peast adds moreadj
    	JButton clearadj = new JButton("Clear Adjectives");//makes a new button called clearadj with the text "Cear Adjectives"
    	clearadj.addActionListener(new clearadjListener());//clearadj adds an actionlistener which is a clearadjlistener()
    	peast.add(clearadj);//peast adds clearadj
    	JLabel spacer3 = new JLabel(" ");//makes a new label called spacer3
    	peast.add(spacer3);//peast adds
    	JButton moreverb = new JButton("Add a Verb");//makes a new button called moreverb with the text "More Verbs"
    	moreverb.addActionListener(new moreverbListener());//moreverb adds an actionlistener which is a moreverblistener()
    	peast.add(moreverb);//peast adds moreverb
    	JButton clearverb = new JButton("Clear Verbs");//makes a new button called clearverb with the text "Clear Verbs"
    	clearverb.addActionListener(new clearverbListener());//clearverb adds an actionlistener which is a clearverbListener()
    	peast.add(clearverb);//peast adds clearverb
    	JLabel savespacer = new JLabel(" ");//makes a new label called savespacer
    	peast.add(savespacer);//peast adds savespacer
    	JButton savewords = new JButton("Save Words");//makes a new button called save words
    	savewords.addActionListener(new savewordsListener());//savewords adds an actionlistener which is a savewordsListener()
    	peast.add(savewords);//peast adds savewords
    	JButton savesession = new JButton("Save Phrases");//creates a new button called savesession with the text "Save Phrases"
    	savesession.addActionListener(new savesessionListener());//savesession adds an actionlistener which is a savesessionListener()
    	peast.add(savesession);//peast adds savesession
    	JLabel quickspacer = new JLabel(" ");//makes a new label called quickspacer
    	peast.add(quickspacer);//peast adds quickspacer
    	JButton quick1 = new JButton("Word Arrangement 1");//makes a new button called quick1 with the text "Quickie Button 1"
    	quick1.addActionListener(new quick1Listener());//
    	peast.add(quick1);
    	JButton quick2 = new JButton("Word Arrangement 2");
    	quick2.addActionListener(new quick2Listener());
    	peast.add(quick2);
    	JButton quick3 = new JButton("Word Arrangement 3");
    	quick3.addActionListener(new quick3Listener());//100
    	peast.add(quick3);
    	
    	JPanel pwest = new JPanel();
    	pwest.setLayout(new BoxLayout(pwest,BoxLayout.Y_AXIS));
    	JPanel bigpanel2 = new JPanel();
    	bigpanel2.add(pwest);
    	
    	
    	
    	Font midfont = new Font("Comic Sans MS", Font.BOLD, 18);
    	midgui = new JTextArea(10,20);
    	midgui.setEditable(false);
    	midgui.setLineWrap(true);
    	midgui.setFont(midfont);
    	JScrollPane scroll = new JScrollPane(midgui);
    	scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    	scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    	pcenter.add(scroll);
    	
    	
    	
    	
    	nounbox1 = new JTextField("Noun	");
    	nounbox2 = new JTextField("Noun	");
    	nounbox3 = new JTextField("Noun	");
    	JLabel spacer4 = new JLabel(" ");
    	pwest.add(nounbox1);
    	nounbox1.addActionListener(this);
    	pwest.add(nounbox2);
    	nounbox2.addActionListener(new nounbox2Listener());
    	pwest.add(nounbox3);
    	nounbox3.addActionListener(new nounbox3listener());
    	pwest.add(spacer4);
    	adjbox1 = new JTextField("Adjective  ");
    	adjbox2 = new JTextField("Adjective  ");
    	adjbox3 = new JTextField("Adjective  ");
    	JLabel spacer5 = new JLabel(" ");
    	pwest.add(adjbox1);
    	adjbox1.addActionListener(new adjbox1Listener());
    	pwest.add(adjbox2);
    	adjbox2.addActionListener(new adjbox2Listener());
    	pwest.add(adjbox3);
    	adjbox3.addActionListener(new adjbox3Listener());
    	pwest.add(spacer5);
    	verbbox1 = new JTextField("Verb  ");
    	verbbox2 = new JTextField("Verb  ");
    	verbbox3 = new JTextField("Verb  ");
    	pwest.add(verbbox1);
    	verbbox1.addActionListener(new verbbox1Listener());
    	pwest.add(verbbox2);
    	verbbox2.addActionListener(new verbbox2Listener());
    	pwest.add(verbbox3);
    	verbbox3.addActionListener(new verbbox3Listener());
    	JPanel psouth = new JPanel();
    	JPanel bigpanel3 = new JPanel();
    	bigpanel3.add(psouth);
    	phrasemaker = new JButton("Make A Phrase!");
    	phrasemaker.addActionListener(new phrasemakerListener());
    	psouth.add(phrasemaker);
    	boxleft.add(nounbox1);
    	boxleft.add(nounbox2);
    	boxleft.add(nounbox3);
    	Box.createVerticalGlue();
    	boxleft.add(adjbox1);
    	boxleft.add(adjbox2);
    	boxleft.add(adjbox3);
    Box.createVerticalGlue();
    	boxleft.add(verbbox1);
    	boxleft.add(verbbox2);
    	boxleft.add(verbbox3);
    	frame.setSize(800,600);//sets the size of the JFrame
    	frame.setVisible(true);//sets the ability to see the JFrame
    	
    	
    	frame.getContentPane().add(BorderLayout.EAST, bigpanel);
    	frame.getContentPane().add(BorderLayout.WEST, boxleft);
    	frame.getContentPane().add(BorderLayout.SOUTH, bigpanel3);
    	frame.getContentPane().add(BorderLayout.CENTER, scroll);
    
    }
    public void actionPerformed(ActionEvent e) {
    	
    	
    }
    class phrasemakerListener implements ActionListener{
    	public void actionPerformed(ActionEvent ev) {
    		try{
    			
    			
    			nouns.add(nounbox1.getText());
    			nouns.add(nounbox2.getText());
    			nouns.add(nounbox3.getText());
    			adjectives.add(adjbox1.getText());
    			adjectives.add(adjbox2.getText());
    			adjectives.add(adjbox3.getText());
    			verbs.add(verbbox1.getText());
    			verbs.add(verbbox2.getText());
    			verbs.add(verbbox3.getText());
    			
    			
    			
    			
    		midgui.append(getPhraseAra() + "\n ");
    		phrasemaker.setText("Make Another!");
    		}
    		catch(Exception ex){
    		ex.printStackTrace();	
    		}
    	}
    	
    }
    
    class morenounListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		nouns.add(nounbox1.getText());
    		nounbox1.setText("");
    		
    	}
    	
    }
    class clearnounListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class moreadjListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		adjectives.add(adjbox1.getText());
    		adjbox1.setText("");
    		
    	}
    	
    }
    class clearadjListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class moreverbListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		verbs.add(verbbox1.getText());
    		verbbox1.setText(""); 
    		
    	}
    	
    }
    class clearverbListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class savewordsListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		try{
    			FileOutputStream fileout = new FileOutputStream("words.pb");
    		ObjectOutputStream out = new ObjectOutputStream(fileout);
    		
    		out.writeObject(nouns);
    		out.close();
    		midgui.append("words saved");
    		}catch(IOException ex){
    			ex.printStackTrace();
    		}
    	}
    	
    }
    class savesessionListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 try{
    			 JFrame frame = new JFrame();
    			 savefield = new JTextField("Untitled.txt");
    			 JButton save = new JButton("Save");
    			 save.addActionListener(new savebuttonListener());
    			 frame.setVisible(true);
    			 frame.setLayout(new FlowLayout());
    			 frame.add(savefield);
    			 frame.add(save);
    			 frame.setSize(400,75);
    			 
    		 }catch(Exception x){
    			 x.printStackTrace();
    		 }
    		
    	}
    	
    }
    class quick1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    	setPhraseAra();	 
    		
    	}
    	
    }
    class quick2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class quick3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class nounbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class nounbox3listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	}
    class adjbox1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class adjbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class adjbox3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class verbbox1Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		 
    		
    	}
    	
    }
    class verbbox2Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class verbbox3Listener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class midguiListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		
    		
    	}
    	
    }
    class savebuttonListener implements ActionListener{
    
    	public void actionPerformed(ActionEvent e) {
    		try{
    			String fileName = savefield.getText();
    		FileWriter writer = new FileWriter(fileName);
    		 writer.write(midgui.getText());
    		 writer.close();
    		 
    		}catch(IOException ex){
    			ex.printStackTrace();
    		}
    		
    	}
    	
    }
    public void establishConnection(){
    	try{
    	Socket sock = new Socket("192.168.0.195", 5620);
    	
    	}catch(Exception ex){
    		midgui.append("Couldn't get connection");
    	}
    }
    public void setPhraseAra(){
    	p = a;
    	a = funny2;
    		
    }
    public String getPhraseAra(){
    	return a;
    }
    }
    Error:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Phrasebot.<init>(Phrasebot.java:48)
    at Phrasebot.main(Phrasebot.java:64)

  2. #2
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: ArrayIndexOutOfBoundsException?

    Have a look at line 48 of your Phrasebot class (the clue is in the exception message...). ran1, ran2 or ran3 are calculated during the initialisation of your class; nouns, adjectives and verbs are empty and consequently nounarray, adjarray and verbarray. The rann indexes are all out of bounds then. You'll have to move this part of the code to a method to execute after all variables have been initialised (and the lists are populated).

    Also notice you are assigning the same string to funny1, funny2 and funny3. I guess your intention was to get a different result each time; if so, you'll have to recalculate the indexes before each assignment to funnyn.
    Last edited by jcaccia; June 16th, 2009 at 06:57 PM.

  3. #3
    Join Date
    May 2009
    Location
    New Jersey, US
    Posts
    42

    Re: ArrayIndexOutOfBoundsException?

    I see where you're coming from but moving that would cause it to not be able to change the arrangement.
    Sorry, I'm 12 years old and sort of a programming newbie in general.

  4. #4
    Join Date
    Feb 2008
    Posts
    966

    Re: ArrayIndexOutOfBoundsException?

    What he is say is when you do this:

    ArrayList<String> adjectives = new ArrayList<String>();

    and then this:

    String[] adjarray = adjectives.toArray(new String[adjectives.size()]);

    The adjectives Object (of type ArrayList<String>) is empty. Therefore you are creating a new array of size 0. You are essentially creating an array that cannot hold any elements. Threrefore when this code runs:

    int countadj = adjarray.length;
    int countverb = verbarray.length;

    int ran1 = (int) (Math.random() * countverb);
    int ran2 = (int) (Math.random() * countadj);
    int ran3 = (int) (Math.random() * countnoun);

    String funny1 = adjarray [ran2]+ " " + nounarray [ran3]+" " + verbarray [ran1]+" ";
    String funny2 = adjarray [ran2]+ " " + nounarray [ran3]+" " + verbarray [ran1]+" ";
    String funny3 = adjarray [ran2]+ " " + nounarray [ran3]+" " + verbarray [ran1]+" ";


    You are going to get an "ArrayOutOfBoundsException" because you are trying to access adjarray[0] (which is the first element in an array, remember they are 0 indexed), which doesn't exist.

  5. #5
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: ArrayIndexOutOfBoundsException?

    I don't see why you want to build those strings there, they won't change and you are only using funny2 in the setPhraseAra method. You could build those random strings in that method instead of trying to build them in the class initialisation (which doesn't work). For instance, you could use this:
    Code:
    ...
    public void setPhraseAra(){
    	int ran1 = (int) (Math.random() * verbs.size());
    	int ran2 = (int) (Math.random() * adjectives.size());
    	int ran3 = (int) (Math.random() * nouns.size());
    	p = a;
    	a = adjectives.get(ran2) + " " + nouns.get(ran3) + " " + verbs.get(ran1);
    }
    ...
    You don't even need to convert the ArrayLists to arrays.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured