This program I thought was working fine. It reads something I type in then it's supposed to break up the words (or random letters) separated by a " " and pop them into array arr. It works, well sometimes... I don't know what's stopping it and them other times allowing it but it is saying my second array ar2 is trying to take too much input that isn't available...

Here's the snippet of the problem area:

while(flag){
			if (e.getSource() == analyze){
				input = textinput.getText();
				arr = input.split(" ");
				int[] ar2 = new int[arr.length];
				
				for(int a = 0; a<arr.length ; a++){
					test = arr[a];
					int j = (test.length());
					
				int z = ar2[j];
					z++;
					ar2[j]=z;}

The highlighted area is what it's flagging as the problem line below is the full code and the error report.

To get this error the input I gave was: a bb ccc dddd

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4
	at Tracey_Ryan_groupD.actionPerformed(Tracey_Ryan_groupD.java:93)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.util.*;

public class Tracey_Ryan_groupD extends JPanel implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JPanel board; // Panel for buttons
	JPanel canvas; // Panel for drawing on
	JPanel text; // Panel for the text 
	JButton analyze, reset;
	JTextArea textinput;
	JScrollPane areaScrollPane;
	boolean flag=true;
	String input="", output="", test;
	String [] arr;
	
	public Tracey_Ryan_groupD() {

		super(true); // Call constructor of parent

		// Standard layout (flow)
		setLayout(new FlowLayout());

		// Set up two panels, control board and canvas
		board = new JPanel(true);
		canvas = new JPanel(true);
		text = new JPanel(new BorderLayout());
		board.setPreferredSize(new Dimension(100, 69));
		canvas.setPreferredSize(new Dimension(300, 300));
		board.setBorder(BorderFactory.createLineBorder(Color.black));
		canvas.setBorder(BorderFactory.createLineBorder(Color.blue));

		// Create buttons and attach listeners
		analyze = new JButton("Analyze");
		analyze.addActionListener(this);
		
		reset = new JButton("Reset");
		reset.addActionListener(this);

        //Create an editor pane.
        textinput = new JTextArea();
        textinput.setLineWrap(true);
        textinput.setWrapStyleWord(true);
        areaScrollPane = new JScrollPane(textinput);
        areaScrollPane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        areaScrollPane.setPreferredSize(new Dimension(250, 250));
        areaScrollPane.setBorder(
            BorderFactory.createCompoundBorder(
                BorderFactory.createCompoundBorder(
                               BorderFactory.createTitledBorder("Input Text Here:"),
                                BorderFactory.createEmptyBorder(5,5,5,5)),
                areaScrollPane.getBorder()));
        text.add(areaScrollPane,BorderLayout.CENTER);
        
		add(canvas);
		add(board);
		board.add(analyze);
		board.add(reset);
        add(text, BorderLayout.LINE_START);
	}
	
	public void actionPerformed(ActionEvent e) {

		
		while(flag){
			if (e.getSource() == analyze){
				input = textinput.getText();
				arr = input.split(" ");
				int[] ar2 = new int[arr.length];
				
				for(int a = 0; a<arr.length ; a++){
					test = arr[a];
					int j = (test.length());
					
					int z = ar2[j];
					z++;
					ar2[j]=z;}
				
				
				for(int u=1 ; u<ar2.length ; u++)
				
				if (ar2[u]==1){ //More than 1 word
				System.out.println("There was "+ar2[u]+", "+u+" letter word.");
				flag=false;}		
				
				else if (ar2[u]!=0){ //Just 1 word
				System.out.println("There were "+ar2[u]+", "+u+" letter words.");
				//binarySearch(int[]ar2,>0);
				flag=false;
				}

			}
			else if (e.getSource() == reset) {
				flag=false;
				textinput.setText("");
				}
			}
			Graphics g1 = canvas.getGraphics();
			g1.clearRect(1, 1, 298, 298);//because it is 300x300 but the border is 1px on each side thus, 298.
			g1.drawString(output, 10, 20);//10, 20 keeps it neat in corner.
			flag=true;
	}
	public static void main(String[] args) {
		// Create a Tracey_Ryan_groupD entity
		Tracey_Ryan_groupD b = new Tracey_Ryan_groupD();

		// Set up outer frame, and its exit behaviour
		JFrame frame = new JFrame("Text Analyzing");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Set the main content frame to be the Blob,
		// size the frame (pack) and make it visible
		frame.setContentPane(b);
		frame.pack();
		frame.setVisible(true);

	}
}

Thank you so much for looking at this.
Regards,
/\ccendo

Recommended Answers

All 13 Replies

Because you're trying index into an array using an index value representing the length of one the Strings stored in the array. What did you hope to achieve by doing that?

Ok so if I call arr[a] and ATM a=2 I then check the length which happens to be 3 (using ccc as in the above example.) Then I jump to that index in ar2 to add one to that indexes number which in the example of a bb ccc dddd ar2[0]=don't print, ar2[1]=1, ar2[2]=1, ar2[3]=1 and ar2[4]=1.

Having typed this out... should I be putting my numbers starting at 0? I just added the corresponding number to the certain index instead of starting at 0 to save any lite confusion on my side...

Okay? And if your first array is only 3 elements long (which is what you use to create the second array so it is also only 3 elements long, i.e. last index of 2) and one of the Strings is 6 characters long, what happens?

If you want to do it this way, then you need to find the longest String first, and make your second array that length (that length + 1 actually, since arrays are 0 based).

You sir, are the freakin' man, noticed another problem just based on your first question and now I fixed it -- THANKS SO MUCH!!!!!

Oh onemore question if its ok in this topic, basedon my above code, how would I print out my information to the JPanel canvas?

Forgot how to do that just been using System.out.println atm to test results.

Thanks so much again!

By calling repaint on the canvas after modifying the graphics object?

I'm not quite, sure never played with the graphics object myself it was already inside this code when I got it as a fragment.

Well look at the code. What do think this " g1.drawString(output, 10, 20);//10, 20 keeps it neat in corner. " is doing?

I've been trying to read up on this method :S -- I assume it will print out output in x,y position 10,20.

What is "g1" (hint, you can find it two lines higher in the code)?

Edit: And then read reply #7 again.

I can see it is of type Graphics and it says -- g1 = canvas.getGraphics(); and I know canvas is my JPanel but other than that I'm not sure what g1 is...

I think from just re-reading, is g1 calling canvas' shape i.e, 300x300 which is why it says 298x298 because if it cleared the shape by 300x300 then it would remove the border. But I'm stillnot sure how to use g1 to write something.

Oops, I've just seen I can edit and play with that object... I had vainly made it into a method because some other program I had did that... NVM!!!

I've not tried this yet, just following up on my post, but is it simple to print out an array line by line? I'm guessing at the moment if I just threw it into a loop it would print all the text on top of each other, if so, how would I make it pop down a line please!?

EDIT: I meant to say is it possible to make it pop down a line without playing with the -- g1.drawString("string", 10, 20) << x,y position

EDIT2: I got it all working printing out beautifully in that box! ... but sadly I had the problem I expected :S -- Is there a more basic way of making my program just press RETURN as opposed to me having to adjust pixels each time?

NVM Thank your very much masijade!

My code works fine, and I'd like to just post it here as a finished product you helped create ^_^.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.*;

import javax.swing.*;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import java.util.*;

public class Tracey_Ryan_groupD extends JPanel implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String JLabel = null;
	JLabel label;
	JPanel board; // Panel for buttons
	JPanel canvas; // Panel for drawing on
	JPanel text; // Panel for the text 
	JButton analyze, reset;
	JTextArea textinput;
	JScrollPane areaScrollPane;
	boolean flag=true;
	String input="", output="", test;
	String [] arr;
	
	public Tracey_Ryan_groupD() {

		super(true); // Call constructor of parent

		// Standard layout (flow)
		setLayout(new FlowLayout());

		// Set up two panels, control board and canvas
		board = new JPanel(true);
		canvas = new JPanel(true);
		text = new JPanel(new BorderLayout());
		board.setPreferredSize(new Dimension(100, 69));
		canvas.setPreferredSize(new Dimension(300, 300));
		board.setBorder(BorderFactory.createLineBorder(Color.black));
		canvas.setBorder(BorderFactory.createLineBorder(Color.blue));

		// Create buttons and attach listeners
		analyze = new JButton("Analyze");
		analyze.addActionListener(this);
		
		reset = new JButton("Reset");
		reset.addActionListener(this);

        //Create an editor pane.
        textinput = new JTextArea();
        textinput.setLineWrap(true);
        textinput.setWrapStyleWord(true);
        areaScrollPane = new JScrollPane(textinput);
        areaScrollPane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        areaScrollPane.setPreferredSize(new Dimension(250, 250));
        areaScrollPane.setBorder(
            BorderFactory.createCompoundBorder(
                BorderFactory.createCompoundBorder(
                               BorderFactory.createTitledBorder("Input Text Here:"),
                                BorderFactory.createEmptyBorder(5,5,5,5)),
                areaScrollPane.getBorder()));
        text.add(areaScrollPane,BorderLayout.CENTER);
        
		add(canvas);
		add(board);
		board.add(analyze);
		board.add(reset);
		
        add(text, BorderLayout.LINE_START);
	}
	
	public void actionPerformed(ActionEvent e) {
		int q=0, p=0, h=20;
		
		while(flag){
			if (e.getSource() == analyze){
				Graphics g1 = canvas.getGraphics();
				g1.clearRect(1, 1, 298, 298);
				input = textinput.getText();
				arr = input.split(" ");
				
				while(p<arr.length){
					test=arr[p];
					int r = test.length();
					if(r>q){
						q=r;
					}
					p++;
				}
				
				int[] ar2 = new int[q];
				
				for(int a = 0; a<arr.length ; a++){
					test = arr[a];
					int j = (test.length());
					int z = ar2[j-1];
					z++;
					ar2[j-1]=z;}
				
				//This is the printing loop
				for(int u=0 ; u<ar2.length ; u++){
				
					//Graphics g1 = canvas.getGraphics();
					//g1.clearRect(1, 1, 298, 298);//because it is 300x300 but the border is 1px on each side thus, 298.
					//g1.drawString("hi", 10, 20);//10, 20 keeps it neat in corner.
					//flag=true;
				
					
				if (ar2[u]==1){ //Just 1 word
				g1.drawString("There was 1, "+(u+1)+" letter word.",10,h);
				h+=15;
				flag=false;}		
				
				else if (ar2[u]!=0){ //More than 1 word
				g1.drawString("There were "+ar2[u]+", "+(u+1)+" letter words.", 10, h);
				//System.out.println("There were "+ar2[u]+", "+(u+1)+" letter words.");
				//binarySearch(int[]ar2,>0);
				h+=15;
				flag=false;
				}
				}//The end of the printing loop
				
			}
			
			else if (e.getSource() == reset) {
				Graphics g1 = canvas.getGraphics();
				g1.clearRect(1, 1, 298, 298);
				flag=false;
				textinput.setText("");
				}
			
		}
			//Graphics g1 = canvas.getGraphics();
			//g1.clearRect(1, 1, 298, 298);//because it is 300x300 but the border is 1px on each side thus, 298.
			//g1.drawString("hi", 10, 20);//10, 20 keeps it neat in corner.
			flag=true;
		}
		
	public static void main(String[] args) {
		// Create a Tracey_Ryan_groupD entity
		Tracey_Ryan_groupD b = new Tracey_Ryan_groupD();

		// Set up outer frame, and its exit behaviour
		JFrame frame = new JFrame("Text Analyzing");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Set the main content frame to be the Blob,
		// size the frame (pack) and make it visible
		frame.setContentPane(b);
		frame.pack();
		frame.setVisible(true);

	}
}

Regards,
/\ccendo

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.