-1

I am still pretty new to learning java and for an assignment I was given a set of data to run with my code.

enter image description here

After inputting some of the data, this exception appeared

enter image description here

I can't figure out why an exception is being thrown after I prompt user for money tended by the customer. Help is appreciated. Here is my code below:

public class cashRegister 
{
    public static void main(String[] args)
    {
        //represents the sale amount
        double saleAmt;
        //represents amount of money given by customer
        double cusTend;
        //represents customer's change 
        double cusChange = 0;

        //Collects sale amount from user
        Scanner customerIn = new Scanner(System.in);
        System.out.println("Please enter the sale amount");
        saleAmt = customerIn.nextDouble();
        //Collects amount tended 
        System.out.println("Please enter amount tended by the customer");
        cusTend = customerIn.nextDouble();
        //Outputs customer's total change
        cusChange = cusTend - saleAmt;
        System.out.printf("Total Change: %.2f", cusChange,"\n");
        //Splits change into Dollars and Cents 
        DecimalFormat decimalFormat = new DecimalFormat();
        String moneyString = decimalFormat.format(cusChange);
        String[] parts = moneyString.split("\\.");
        String part2 = parts[1]; //ArrayIndexOutOfBoundException here
        String dollars= parts[0];
        double cents5 = Double.parseDouble(part2);
        //Divides change by amount
        int cents = (int)cents5;
        int quarters = cents / 25;
        int cents1 = cents % 25;
        int dimes = cents1 / 10;
        int cents2 = cents % 10;
        int nickels = cents2 / 5;
        int cents3 = cents % 5;
        int pennies = cents3;

        //Out prints the amount of dollars, quarters, dimes, nickles, and pennies 
        System.out.printf("\n"+ "Dollars :"+ dollars + "\n" );
        System.out.printf("Quarters :" + quarters + "\n");
        System.out.printf("Dimes :"+ dimes +"\n");
        System.out.printf("Nickles :" + nickels +"\n");
        System.out.printf("Pennies :" + pennies + "\n");

    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41
  • My guess would be `moneyString.split("\\.");` returns an array of 1 element. – Old Dog Programmer Sep 22 '22 at 02:37
  • By the way, the exception will point to a line number in your code. You could mark the line in the code you copy here. For example: `int foo = bar / bin; // **** Division by zero exception here ****` – Old Dog Programmer Sep 22 '22 at 02:41
  • See this question: https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – Old Dog Programmer Sep 22 '22 at 02:48
  • 1
    @OldDogProgrammer Thank you! I updated my post to show which line it was pointing to. I read the thread that you linked and I'm still a little confused. (This was a sample code my tutor told me to follow and it wasn't explained well) – maddie pattie c Sep 22 '22 at 02:51
  • I would advise against using a floating point type (`double` or `float`) to represent money. It doesn't work well with decimal fractions. Try using an `int` variable that represents cents. Or use `BigDecimal`. – Old Dog Programmer Sep 22 '22 at 03:00

1 Answers1

1

When sale amount is 92 and amount tended is 95, the total change is 3. Hence moneyString is 3 and not 3.00 Therefore moneyString.split("\\.") will return an array that contains a single element only and that's why you are getting ArrayIndexOutOfBoundException.

You just need to check the number of elements in parts and add code that handles different numbers of elements. Also, as mentioned in the comments, it is better to use class java.math.BigDecimal for money amounts (rather than double). Refer to this SO question (and answer): How to display a number with always 2 decimal points using BigDecimal?

Note that there is also Java Money.

It is recommended to adhere to Java naming conventions which means that then name of your class should be CashRegister (and not cashRegister). Remember that Java code is case-sensitive.

Here is my rewrite of your code. I check the number of elements in parts and handle the case where that number is zero or one or two.

Refer to the javadoc for method printf, I think you should change the code that calls that method. I have done so in the below code.

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;

public class CashRegister {

    public static void main(String[] args) {

        //Collects sale amount from user
        Scanner customerIn = new Scanner(System.in);
        System.out.println("Please enter the sale amount");
        double tmp = customerIn.nextDouble();

        //represents the sale amount
        BigDecimal saleAmt = new BigDecimal(tmp);

        //Collects amount tended 
        System.out.println("Please enter amount tended by the customer");
        tmp = customerIn.nextDouble();

        //represents amount of money given by customer
        BigDecimal cusTend = new BigDecimal(tmp);

        //Outputs customer's total change
        BigDecimal cusChange = cusTend.subtract(saleAmt);
        cusChange.setScale(2, RoundingMode.HALF_UP);

        //Splits change into Dollars and Cents
        String moneyString = String.format("%.2f", cusChange.doubleValue());
        System.out.printf("Total Change: %s%n", moneyString);
        String[] parts = moneyString.split("\\.");
        String dollars;
        if (parts.length > 0) {
            dollars = parts[0];
        }
        else {
            dollars = "0";
        }
        String part2;
        if (parts.length > 1) {
            part2 = parts[1];
        }
        else {
            part2 = "0";
        }
        double cents5 = Double.parseDouble(part2);

        //Divides change by amount
        int cents = (int)cents5;
        int quarters = cents / 25;
        int cents1 = cents % 25;
        int dimes = cents1 / 10;
        int cents2 = cents % 10;
        int nickels = cents2 / 5;
        int cents3 = cents % 5;
        int pennies = cents3;

        //Out prints the amount of dollars, quarters, dimes, nickles, and pennies 
        System.out.printf("%nDollars : %s%n", dollars);
        System.out.printf("Quarters: %d%n", quarters);
        System.out.printf("Dimes   : %d%n", dimes);
        System.out.printf("Nickles : %d%n", nickels);
        System.out.printf("Pennies : %d%n", pennies);
    }
}

Here is a sample run of the above code:

Please enter the sale amount
92.00
Please enter amount tended by the customer
95.00
Total Change: 3.00

Dollars : 3
Quarters: 0
Dimes   : 0
Nickles : 0
Pennies : 0
Abra
  • 19,142
  • 7
  • 29
  • 41