Results 1 to 9 of 9
  1. #1
    paul is offline Member
    Join Date
    Jul 2007
    Posts
    26
    Rep Power
    0

    Default Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

    Hi, I have enrolled into Java classes and got this problem that i have mostly figured out how to do, but my application gives me an error when i run it. I understand that there is a mistake, but i can't figure out what is causing it and if it can be fixed.

    The application is from a Java texbook, and its purpose is to calculate sales comissions.
    Java Code:
    at $200 base + 9% of sales = salary.
    I'm using an array to feed the sales figures, then trying to do the math upon the values of the array and count how many salesmen fit into the ranges of salaries between:
    Java Code:
    200-299
    300-399
    ....
    1000 and more.
    Here is my code:

    Java Code:
    public class Salary 
    {
    
    	public static void main(String[] args) 
    	{
    		double salary[]={300, 200, 600, 700, 2000, 8000, 800, 800, 900, 6000, 1100};
    		int frequency []= new int [11];
    		System.out.printf("%10s: %6s:\n","Range", "Frequency");
    		for (int range = 0; range < (salary.length); range++)
    			++frequency[(int)Math.floor(((salary[range]*(.9)+200)*.01))];
    
    		for (int range1 =2; range1<frequency.length; range1++)
    			System.out.printf("$%4d-%4d: %10d\n", range1*100,range1*100+9,frequency[range1]);
    	}
    
    
    }
    Error:

    Java Code:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
    at Salary.main(Salary.java:11)
    I know that if i just feed the numbers without doing the math, the application seems to work, but when i start doing the math, it stops working. I'm using the Math.
    floor in order to get an integer value, which can then be pushed into the frequency array.

    The frequency array should collect the values between 0 and 10 and then print them (as number of people) next to the range of salary.
    Thanks

  2. #2
    coco is offline Member
    Join Date
    Jul 2007
    Posts
    39
    Rep Power
    0

    Default

    Ok, so as the error suggests you are trying to access an array index which is outside the bounds for that array. Take a look at the following code.
    Java Code:
    for (int range = 0; range < (salary.length); range++)
    {
      //Added this print statement so we can see why we're going out of bounds.
      System.out.println((int)Math.floor(((salary[range]*(.9)+200)*.01)));
      ++frequency[(int)Math.floor(((salary[range]*(.9)+200)*.01))];
    }
    You declare frequency as an array of size 11; which means the valid indexes for that variable are frequency[0] to frequency[10].
    If you run your code with the added print statement and look at the numbers that get printed out you'll see that it prints 4,3,7,8,20 which are the numbers that are computed by (int)Math.floor(((salary[range]*(.9)+200)*.01)) for each iteration of the for loop. The error occurs at the computed value of 20.

    If we simplify your code that means you're doing the following in your for loop
    Java Code:
    ++frequency[4]
    ++frequency[3]
    ++frequency[7]
    ++frequency[8]
    ++frequency[20]
    20 is not a valid index of the frequency array. As I previously stated since the array has a length of 11, trying to access the array at an index greater than 10 will give an array out of bounds error.

    This suggests to me that your computation logic is slightly off.

    Greetings.

  3. #3
    Archaic is offline Member
    Join Date
    Mar 2009
    Posts
    1
    Rep Power
    0

    Default

    Hi, I have the same error message with my java document. I was wondering if someone could also help with it. I've tried to change the code up a little here and there but to no avail.

    Here is my declared class file:

    Java Code:
    public class Taxpayer
    {
    	private int numberOfPeople;
    	private int socialSecurityNum;
    	private double yearlyGrossIncome;
    	
    	// A contructor for the Taxpayer class
    	// Called when a new Taxpayer object is created
    	public Taxpayer(int numPPL)
    	{
    		int[] socialSecurity= {0, 123001234};
    		double[] yearlyGross= {0.0, 100};
    		
    		numberOfPeople = numPPL;
    		
    		if(numPPL > socialSecurity.length)
    		{
    			numPPL = 0;
    		}
    		
    		socialSecurityNum = socialSecurity[numPPL];
    		yearlyGrossIncome = yearlyGross[numPPL];
    	}
    	
    	public int getNumberOfPeople()
    	{
    		return numberOfPeople;
    	}
    	public void setNumberOfPeople(int people)
    	{
    		numberOfPeople = people;
    	}
    	
    	public int getSocialSecurityNum()
    	{
    		return socialSecurityNum;
    	}
    	public void setSocialSecurityNum(int SocialSN)
    	{
    		socialSecurityNum = SocialSN;
    	}
    	
    	public double getYearlyGrossIncome()
    	{
    		return yearlyGrossIncome;
    	}
    	public void setYearlyGrossIncome(double yearlyGross)
    	{
    		yearlyGrossIncome = yearlyGross;
    	}
    }
    Here is the driver file:

    Java Code:
    import javax.swing.JOptionPane;
    
    public class UseTaxpayer
    {
    	public static void main(String[] args)
    	{
    		Taxpayer[] someTaxpayers = new Taxpayer[10];
    		int x = 0;
    		
    		for(x = 0; x < someTaxpayers.length; ++x)
    			someTaxpayers[x] = new Taxpayer(1);
    			someTaxpayers[x].setSocialSecurityNum(999999999);
    			someTaxpayers[x].setYearlyGrossIncome(0.00);
    			
    		for(x = 0; x < someTaxpayers.length; ++x)
    			JOptionPane.showMessageDialog(null, "Person number " + x + " \nSocial Security Number: " + someTaxpayers[x].getSocialSecurityNum() + " \nYearly Gross Income: " + someTaxpayers[x].getYearlyGrossIncome() + "", "EventArray.java", JOptionPane.INFORMATION_MESSAGE);
    			
    		System.exit(0);
    	}
    }
    The driver is supposed to initialize the "socialSecurityNum" to 999999999 and "yearlyGrossIncome" to 0.00. I think this should work, but I still keep getting the error when I try to run the compiled .class file.

  4. #4
    mtyoung is offline Senior Member
    Join Date
    Dec 2008
    Location
    Hong Kong
    Posts
    473
    Rep Power
    6

    Default

    Archaic, you should post an new post to ask new question...

    Java Code:
    for(x = 0; x < someTaxpayers.length; ++x)
    	someTaxpayers[x] = new Taxpayer(1);
    	someTaxpayers[x].setSocialSecurityNum(999999999);
    	someTaxpayers[x].setYearlyGrossIncome(0.00);
    have you found something wrong here?

    {} needed

  5. #5
    pdanahey is offline Member
    Join Date
    Mar 2009
    Posts
    1
    Rep Power
    0

    Angry Exercise 7.20 from Java How to Program book

    Okay I got it figured out the most part but running into a problem with it. When I get it to run I get the error:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2: at TotalSales.totalsales.main(totalsales.java:39):mad : I have been working on this for two weeks now and the last day to get this turned in is Saturday by noon central time. Here is my code:

    package TotalSales;

    import java.util.Random;

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    /**
    *
    * @author pdanahey
    */
    public class totalsales
    {
    static Random rand = new Random();
    private static int outer;
    private static int inner;

    public static void main(String[] args)
    {
    int sales[][]=
    {
    {1, 2, 3, 4, },
    {0, 1, 2, 3, 4, 5},
    };
    int counter = 0;
    int innerCount[] = new int[5];

    System.out.printf(" Col 1 Col 2 Col 3 Col 4 \n");

    for (int outer1=0; outer <sales.length; outer++)
    {
    counter = 0;
    System.out.print(" ");
    }


    for ( int inner1=0; inner1 < sales[outer].length; inner1++)
    {
    System.out.printf("%s ", sales[outer][inner1]);
    counter += sales[outer][inner1];
    innerCount[inner1] += sales[outer][inner1];
    }
    System.out.printf("\t%s\n", counter);
    System.out.printf(" %s %s %s\n", innerCount[0], innerCount[1], innerCount[2]);
    }

    }

    If anyone can help me ASAP I will be greatly appreciate it.
    Pam

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    1) please don't hijack someone else's thread. If you have an important question, then please post it in a new thread.
    2) when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?

    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [/cod&#101;] below your pasted code like so:

    Java Code:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]
    Lots of mistakes, but I'm mostly having trouble figuring out what you're trying to do here:
    Java Code:
    for (int outer1=0; outer <sales.length; outer++)
    {
      counter = 0;
      System.out.print(" ");
    }
    But again, don't answer here, please start a new thread.

  7. #7
    rejeeshk is offline Member
    Join Date
    Mar 2011
    Posts
    1
    Rep Power
    0

    Default same Error occurring while running

    import java.net.* ;
    import java.io.* ;
    import java.lang.* ;
    import java.util.* ;

    class proxy {
    public static void main(String args[]) throws IOException{

    //parse arguments from command line

    int localport = -1;
    int remoteport = -1;
    String remotehost = null;
    boolean error = false;

    int i = 0;
    Integer parselocalport = new Integer(args[i]);
    Integer parseremoteport = new Integer(args[i+2]);
    Socket incoming, outgoing = null;
    ServerSocket Server = null;

    try
    {
    localport = parselocalport.parseInt(args[i], 10);
    remotehost = args[i+1];
    remoteport = parseremoteport.parseInt(args[i+2], 10);
    }

    catch(Exception e)
    {
    System.err.println("Error: " + e.getMessage() + "\n");
    error = true;
    }

    // Check for valid local and remote port, hostname not null

    System.out.println("Checking: Port" + localport + " to " + remotehost + " Port " + remoteport);

    if(localport <= 0){
    System.err.println("Error: Invalid Local Port Specification " + "\n");
    error = true;
    }
    if(remoteport <=0){
    System.err.println("Error: Invalid Remote Port Specification " + "\n");
    error = true;
    }
    if(remotehost == null){
    System.err.println("Error: Invalid Remote Host Specification " + "\n");
    error = true;
    }

    //If any errors so far, exit program

    if(error)
    System.exit(-1);


    //Test and create a listening socket at proxy

    try{
    Server = new ServerSocket(localport);
    }
    catch(IOException e) {
    e.printStackTrace();
    }

    //Loop to listen for incoming connection, and accept if there is one

    while(true)
    {
    try{
    incoming = Server.accept();
    //Create the 2 threads for the incoming and outgoing traffic of proxy server
    outgoing = new Socket(remotehost, remoteport);

    proxyThread thread1 = new proxyThread(incoming, outgoing);
    thread1.start();

    proxyThread thread2 = new proxyThread(outgoing, incoming);
    thread2.start();
    }
    catch (UnknownHostException e) {
    //Test and make connection to remote host
    System.err.println("Error: Unknown Host " + remotehost);
    System.exit(-1);
    }
    catch(IOException e){
    System.exit(-2);//continue;
    }

    /* catch (IOException e) {
    System.err.println("Error: Couldn't Initiate I/O connection for " + remotehost);
    System.exit(-1);
    }
    */
    }
    }


    }

    Please Help.....

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,433
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by rejeeshk View Post
    Please Help.....
    Did you read reply #6?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Replies: 1
    Last Post: 08-07-2007, 07:10 AM
  2. Replies: 2
    Last Post: 08-01-2007, 05:26 AM
  3. Replies: 1
    Last Post: 07-31-2007, 01:54 PM
  4. Replies: 1
    Last Post: 07-25-2007, 10:55 PM
  5. Replies: 1
    Last Post: 07-16-2007, 06:32 AM

Posting Permissions

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