Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Advances In Spatial Databases 2nd Symposium Ssd 91 Zurich Switzerland August 1991 Proceedings Lncs 525

Authors: Oliver Gunther ,Hans-Jorg Schek

1st Edition

3540544143, 978-3540544142

More Books

Students also viewed these Databases questions