Skip to main content

ArrayIndexOutOfBoundsException

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
2 replies [Last post]
finfanman
Offline
Joined: 2012-06-24

New to Java. This program is supposed to output the differenc between two sales figures. I cannot figure out what the problem is. A huge thank you for your help.

import java.util.Scanner;

public class Earnings
{
public static void main(String[] args)
{
final int salesReps = 2; //Number of sales reps to compare

double[] sales = new double[salesReps]; //Create array

Scanner keyboard = new Scanner(System.in); //For keyboard input

System.out.println("Enter the total sales amount for "
+salesReps+ " sales representatives to compare. "); //Ask for sales figures

for (int index = 0; index {
System.out.print("Sales representative " + (index +1) + " sold ");
sales

= keyboard.nextDouble();
}
if (sales[0]>sales[2])
{
System.out.println("Sales representative 1 sold"
+(sales[0]-sales[1])+ " more than sales representative 2.");
}
else
{
System.out.println("Sales representative 2 sold"
+(sales[1]-sales[0])+ " more than sales representative 1");
}

}
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kirild
Offline
Joined: 2011-02-17

There's some code missing from the for loop that makes this code invalid. I think the problem is most likely in the line "if (sales[0]>sales[2])". The original assignment of the sales array is for 2 elements only, so I think this line should read "if (sales[0]>sales[1])". If this isn't the problem, could you repost the complete code?

finfanman
Offline
Joined: 2012-06-24

That was exactly the problem. I can't believe I missed that. Thank you so much!