ArrayIndexOutOfBoundsException when Running Data - java

I am still pretty new to learning java and for an assignment I was given a set of data to run with my code.
After inputting some of the data, this exception appeared
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");
}
}

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

Related

Java Coin Change Evaluation

I am currently writing a program that prints only the coins used when returning change. However, I get 2 assertions errors which are evaluated on the server's back-end. There are no sample test values, you have to make up your own.
expected:[... Change Due $0.01 [1 penny] ]
but was:[... Change Due $0.01 [2 pennies] ]
expected:[... Change Due $0.19 [1 dime 1 nickel 4 pennies ]
but was:[... Change Due $0.19 [2 dimes ]
/**
* Calculate the amount of change based on user input.
* Output coins with an output greater than 0.
* #param args returns an argument array for string objects
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Total amount? ");
double total = input.nextDouble();
System.out.print("Cash payment? ");
double payment = input.nextDouble();
double changeDue = payment - total;
System.out.println();
System.out.printf("Change Due $%.2f\n\n", changeDue);
int cents = (int) Math.ceil(changeDue * 100);
int dollars = Math.round((int) cents / 100);
cents = cents % 100;
int quarters = Math.round((int) cents / 25);
cents = cents % 25;
int dimes = Math.round((int) cents / 10);
cents = cents % 10;
int nickels = Math.round((int) cents / 5);
cents = cents % 5;
int pennies = Math.round((int) cents / 1);
int[] coins = {dollars,quarters,dimes,nickels,pennies};
String[] names = {"dollar", "quarter", "dime", "nickel", "penny"};
for (int i = 0; i < 5; i++) {
if (coins[i] == 1) {
System.out.println(coins[i] + " " + names[i]);
} else if (coins[i] > 1 && i != 4) {
System.out.println(coins[i] + " " + names[i] + "s");
}
}
if (coins[4] > 1) {
System.out.println(coins[4] + " pennies");
}
}
Your code actually works fine. But the problem is if you just print your "changeDue" variable and see then you can see there is a 9 at the end. It is printed as 0.010000000000000009 not as 0.010000000000000000 as you would expect it to. Then it is ceiled as 2 after multiplying by 100. Then you get 2 pennies as the answer.
Actually this seems to be a problem with how decimals are stored. (Java Double value = 0.01 changes to 0.009999999999999787) It is explained here nicely. So you might have to change your approach a little bit.
You have made a fairly common mistake in Java. Money cannot be represented by double, they are different things. In Java the closest thing we have to money is called BigDecimal. It's a little more awkward because you can't use arithmetic symbols with it (+-/*^%), but it's a lot more accurate.
There is also a formal specification for money: Money and Currency API (JSR 354), for which there are a couple of implementations including Joda Money and the offical reference implementation.

How to use int output to calculate other output?

Create a Change application that prompts the user for an amount less than $1.00 and then displays the minimum number of coins necessary to make the change.
The change can be made up of quarters, dimes, nickels, and pennies.
Here is what I did:
public static void main(String[] args) {
System.out.println("Enter the amount in cents: ");
int a = in.nextInt();
if(a <= 100){
}else{
System.out.println("Try Again");
System.exit(0);
}
{
int q = (a/25);
int d = (a/25);
System.out.println("Quarters: " + q);
System.out.println("Dimes: " + d);
}
}
}
D is irrelevant. because I don't know how to get the remainder of quarters and divide it by 10 and so on all the way through pennies
To find the remainder of anything, subtract off the amount you've taken.
For free, you need to subtract off the coin price times the amounts as you go.
if(a <= 100){
int q = a/25;
a = a-q*25;
int d = a/10;
a = a-d*10;
}

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Nickles in Coin Counter not displaying correct amount

I was just given my first assignment in my Java class, and we were tasked with creating a program that counts nickles and displays the total amount of money. However, whenever I put an odd number of nickles it does not display the corrent amount of money. For example, 1 nickles turns into $.5 instead of $.05. 21 Nickles turns into $1.5 instead of $1.05. I'm asumming this is an easy fix for an easy problem, but I am finding myself stumped. Thanks for the help.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
int nickles5 = nickles * 5;
int dollars = nickles5 / 100;
int change = nickles5 % 100;
System.out.println("You have $" + dollars + "." + change);
}
I'll go out on a limb here, to try to solve your problem. It appears that you will ask the user to enter some number of nickels, and you will output the amount in dollars. Please let me know if this is incorrect in any way.
Now look at the following code.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
double nickles5 = nickles * 0.05;
System.out.println("You have $" + nickles5);
}
After we have the number of nickels stored in an int, we multiply it by 0.05, to get the actual value of all the nickels. We store this in a double variable [Note: int multiplied to a double, returns a double; it is called numeric promotion]. Now, to get the total value, you can simply print this double variable. In a case where n=2, nickels5 = 0.1. So, it will print $0.1
If you want this to show up as $0.10, simply replace the nickels5 with String.format( "%.2f", nickels5)
Now your final line will look like:
System.out.println("You have $" + String.format( "%.2f", nickels5));
Let me know if this solved your issue.
You need to format change to use 2 digits, rather than just printing out the raw number. Specifically, if change==5, you want to print out 05.
You can do this with String.format("%02d", change)
You have a random apostrophe at the end, why?
You want to use floats instead of ints, like this:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
System.out.println("$"+ amount);
Output:
Deposit your Nickles.
1
$0.05
Deposit your Nickles.
21
$1.05
EDIT: Code with formatted output:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
String output = String.format("%02f", amount);//f(loat) not d
System.out.println("$"+ output);

Change Machine Math & Logic Errors

I've posted this program once before but realized I was overthinking it by adding loops and what not. I've paired it down a bit but still running into problems. The program is supposed to be a change machine. After the user inputs price, the program should round it up to the nearest dollar then output how much change will be dispensed and a count of which coins. The output is completely wrong at this point. I'm very new to programming and I'm at a loss.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price*100);
int paid = (int)(newPrice+1);
int change = (int)(paid - newPrice);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Once newPrice is an int, you can stop casting every line.) Instead of chaining % together, it would be more readable (and less error prone) to subtract off the values you've found:
change -= 25*quarters;
dimes = change / 10;
change -= 10*dimes;
nickels = change / 5;
change -= 5*nickels;
pennies = change;
I think it would help you to understand if you would go through the code by hand and think about what price, newprice, paid, and change are.
newprice is the price round down to the lower dollar.
paid is the cost of the item.
change is the amount you paid minus the cost converted into an integer number of pennies.
package changemachine;
import java.util.Scanner;
import java.text.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
double price = scan.nextDouble();
int newPrice = (int)(price);
int paid = (int)(newPrice+1);
int change = (int)((paid - price) * 100);
int quarters = (int)(change/25);
int dimes = (int)((change%25)/10);
int nickels = (int)((change%25%10)/5);
int pennies = (int) (change%25%10%5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
If instruction int paid= (int)(newPrice+1) ; is supposed to be rounding to next dollar, then it should be: int paid= ( newPrice + 99 ) / 100 * 100 ; You don't need to convert to (int) when both operands are already ints. Makes your program slightly illegible. Later, after obtaining the number of quarters by quarters= change / 25 ;(that's correct in your program), you can reduce the amount fromchangewithchange-= quarters * 25 ;`.
This makes calculating dimes exactly the same as quarters, just that using 10 instead of 25. Don't forget reducing the dimes from the pending change again with change-= dimes * 10 ;. You can repeat the process with nickels and the remaining change will be pennies.
If you have any doubt, use a debugger or output each intermediate result with System.out. You can always delete them later once you understand your program's behavior.
This is how I made Java choose what coins I must pay with.
int temp = m;
int quarterCoin = 25;
int x = m/quarterCoin;
m=m-x*quarterCoin;
int dimeCoin = 10;
int z = m/dimeCoin;
m=m-z*dimeCoin;
int nickelCoin = 5;
int y = m/nickelCoin;
m=m-y*nickelCoin;
int pennyCoin = 1;
int w = m/pennyCoin;
m=m-w*pennyCoin;
Instead of giving you the answer/solution to your homework, I am going to help you figure out how to figure it out. :)
In order to adequately debug your software and troubleshoot what's going on, you need to know what your variables are doing. There are two methods:
Attach a debugger - Most IDEs will come with a debugger that will help you accomplish this.
Print out your variables to the console. This is my preferred method. Me and debuggers never have gotten along well together. :)
So, here is what I would do if I were trying to figure your program out:
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// System.out.println("Enter Purchase Price: ");
double price = 5.65d;//scan.nextDouble();
int newPrice = (int) (price * 100);
System.out.println("newPrice: " + newPrice);
int paid = (int) (newPrice + 1);
System.out.println("paid: " + paid);
int change = (int) (paid - newPrice);
System.out.println("change: " + change);
int quarters = (int) (change / 25);
int dimes = (int) ((change % 25) / 10);
int nickels = (int) ((change % 25 % 10) / 5);
int pennies = (int) (change % 25 % 10 % 5);
System.out.println("Dispensing: " + quarters + " Quarters,"
+ dimes + "Dimes," + nickels + "Nickels,"
+ pennies + "Pennies.");
System.out.println("Program written by Ashley ");
}
}
(Note: Instead of utilizing the scanner, I just manually entered "5.65" into the price variable just to save time)
Which produces the output:
newPrice: 565
paid: 566
change: 1
Dispensing: 0 Quarters,0Dimes,0Nickels,1Pennies.
Program written by Ashley
So, now you can see what your program is doing wrong. Can you spot it?

Categories

Resources