Question
I need help fixing an error in my Java program. I keep getting an Exception in thread main java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for
I need help fixing an error in my Java program. I keep getting an "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2" error.
The program is supposed to take in the number of items the customer is purchasing, sort the numbers from largest to smallest, and then drop the smallest price out of the three because it's a buy 3 get 1 free sale. the numbers I've been using for an example are 400 100 200 350 300 250 so the output/discount would be 400
This is my code:
import java.util.Scanner; import java.util.Arrays;
public class shop{ public static void main(final String[] args) { final Scanner sc = new Scanner(System.in, "US-ASCII"); int totalItems = sc.nextInt(); int buy = 3; int totalSavings = 0; int[] prices = new int[totalItems]; int[] threeByTwo = new int[totalItems / 3]; // asking for the number of items and the total of each item for (int i = 0; i < totalItems; i++) { prices[i] = sc.nextInt(); } int discount = totalItems / 3; // sorts the numbers inputed Arrays.sort(prices);
for (int i = 0; i < discount; i++) { prices[i] = threeByTwo[discount]; //this is the line the error is occuring in buy = buy*2; } // adds the discounts together after dividing for (int i = 0; i <= discount; i++) { totalSavings = threeByTwo[discount] + threeByTwo[i + 1]; } //prints out the total savings System.out.print(totalSavings); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started