Wrong calculation result - java

I have written this short code and I want to let users to enter bank balance.
Then in new confirm dialog box they will choose if they want to enter transaction amount.
If "YES" then they enter either positive or negative numbers.
If entered value is negative so program with subtracts transaction amount from bank balance.
If entered value is positive so program will add transaction value to bank balance.
At the end if user selects "No" button in confirm dialog box so program will terminates with results of calculation!
Question:
when I enter numbers for bank balance and transactions so I get wrong answer!
I tried to user while loop and do while but I still get wrong results!
double total = 0;
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
}
JOptionPane.showMessageDialog(null,total);
1: I enter 1000 dollars as bank balance.
2: I enter 1050 (positive) as transaction amount.
3: I enter -500 (negative value) as transaction amount for second try.
4: Answer is 1500.00 which is wrong!
1000 + 1050 = 2050.00
2050 - 500 = 1550.00
Answer should be 1550
Why answer is wrong???

In this section:
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
You are updating your total, but not the balance. From the snippet you made, that remains unchanged.
As pointed out by #Fildor down in the comments below, at the moment you have a bug since you are either adding positive numbers together or else, subracting a negative number (x - (-y) == x + y)). To fix this, simply replace the entire if block with total = balance + trc.
You would need to update your balance to have the same value of total, or else, do without total altogether and use the balance field.

You should do something like the following:
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
balance += trc;
}
JOptionPane.showMessageDialog(null,balance);
First, you need to replace your if statement with a += statement. This is because subtracting when trc is negative and adding when trc is positive is equivalent to adding the absolute value of trc every time, which is probably not what you want to do. Second, you need to use 1 variable for balance, and track the changes over time. total is meaningless in the previous code, as it overrides its own value every time that your if statement executes.

double updatedBalance = (trc < 0) ? balance - trc : balance + trc;
total = updatedBalance;
Like the above answer suggests you need to update the balance.

Related

Program getting stuck in while loop?

I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.
Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.

Why isn't the entered money incrementing onto the previous balance? (in Java)

I am creating a bankteller loop java code. I am trying to ask the user for what amount of money they would like to deposit into their account. I can get this to work once. For example, they will enter in $20 the first time. Then they will decide to put in $10 more. However, instead of displaying the current balance at $30, it only displays the one recently entered (the $10). How do I fix this?
Here is my code for that part of the loop in the menu that calls the class:
else if( userInput == 3 ){
Account account = new Account();
System.out.print("\nHow much would you like to deposit?: ");
float money = input.nextFloat();
account.deposit(money);
}
Here is the code for deposit that is called:
public void deposit(float money) {
if (money < 0) {
System.err.println("Error: Can't deposit negative money.\n");
return;
}
else {
currentBalance = money + currentBalance;
System.out.println("Current balance: $" + currentBalance + "\n");
}
}
You want to maintain the total balance so far. However, the moment you create a new Account object, balance gets initialized to zero and thus losing previous balance.
What you need to do is create an Account object only once and then call deposit on the same Account object.

program quitting before its meant to be finnished

So im making a program for an assesment acts as a vending machine, asks you how many cans you would like to purchase and then calculates the values, asks for coins input (assuming the user is being sensible) and then tries to calculate the change given.
The problem i am running in to is that after the program reads in the values for the payment and calculates if it is enough with the following:
double coins[] = new double[]{2.00,1.00,0.50,0.20,0.10,0.05};
//A while loop so that it continues to go until the payment is equal or more than the cost
int count2 = 1;
while (payment <= totalCost){
if (payment == totalCost){
System.out.println("You have entered the exact amount of change! Thankyou.");
break;
}
System.out.println("Please enter more coins: ");
coinsIn[count2] = kbd.nextDouble();
payment = payment + coinsIn[count2];
count2++;
}
It just ends the program.
The problem is, that directly after that while loop i have this sample of code
double change = payment - totalCost;
int count3 = 0;
if ((change == coins[count3]) && (count3 <6)) {
System.out.println("Your change is: ");
System.out.println(change);
}
else{
count3++;
}
That should run, but just doesn't.
For instance say the total cost is $4.50 and i enter in 2 x 2.00 and 1x 1.00 it should run through that if loop and find that in the coins[] there is a .50 value at coins[2], then print the message for the change and then quit.
This is the working example in the terminal:
Please enter the amount of cans that you would like to purchase:
1
Please enter the amount of cans that you would like to purchase:
1
Please enter the amount of cans that you would like to purchase:
1
There are currently [297] cans remaining.
The total cost of your purchase is [$4.5].
Please enter your payment now:
2.00
Please enter more coins:
2.00
Please enter more coins:
1.00
It just ends right after that 1.00,
I do not understand what is going on here.
Any help would be much appreciated.
P.S. Everything compiles fine.
Try changing the initialization of count3 variable. Are you sure with the usage of count3??

Shipping Program

So I seem to have put together majority of this program correctly. Ask I skim through I realized I missed something and go back and add it in. Now as I run the program for a final test I realize that it is no longer calculating the miles correctly. I input 500 for example and will get 1 in return for number of miles shipped.
input = JOptionPane.showInputDialog("Enter package weight: ");
weight = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Enter approximate miles package is being shipped: ");
miles = Integer.parseInt(input);
miles = (miles+499)/500;
input = JOptionPane.showInputDialog("Enter number of units shipped: ");
units = Integer.parseInt(input);
I know I am not doing the math correctly in order to find the correct amount charged per unit but what is concerning for now is the miles being shown incorrectly in my output. Any suggestions? Thanks!
Assuming miles is declared as double (if it's not, you should declare it as double so you can assign it a real number). This line
miles = (miles+499)/500;
is making a integer division (int/int = int). To get a double, you must cast it:
miles = (double)(miles+499)/500;
or, as #Vulcan suggested
miles = (miles+499)/500.0; // here 500.0 is a double
It seems like the data type of miles variable is int.Please change it to double and re-run the application.
Also as per ur comment updating the logic :
Let the input you entered is :
double weight = 7; //input
double miles = 550; //input
double unit = 2; //input
double charges =0; //charge of the shipment initialise with 0
charges = (3.70*miles*unit*weight)/(500*7);
System.out.println("The charges is "+charges);
The charges of 1 unit is $3.70 per 7 pound weight per 500 miles.
Also update the existing code :
miles = Integer.parseInt(input); //Use double as conversion
miles = (miles+499)/500; // remove the line

giveChange method computes change and number of coins to return java?? [duplicate]

This question already has answers here:
min change greedy algorithm in java
(2 answers)
Closed 8 years ago.
I have a cashregister program that inputs purchases and payment and outputs the change due. i need it to not give just an amount but what particular coins/dollars user should get back. heres two methods i have
public void recordPurchase()
{
System.out.print("Enter total purchase price or negative number to end: ");
double input = keyboard.nextDouble();
while(input > 0)
{
purchase = purchase + input;
System.out.print("Enter total purchase price or negative number to end: ");
input = keyboard.nextDouble();
}
}
public double giveChange(Money moneyTypes)
{
double change = payment - purchase;
purchase = 0;
payment = 0;
//computes change rounding to two decimal places
change = (double)(Math.round(change*100))/100;
return change;
}
I need to output what coins/dollars person should get back. i have the money types saved in an array called moneyTypes. for example if the change due is $1.06 it would output you receive a dollar nickel and penny.
any advice would help. Thanks! if you need to see more of the code let me know
I'll give you an advice how to do it, not a solution.
Make a list of possible coin/note values.
Then from the biggest to lowest, compute how many times it fits into the remainder, and subtract this amount of money from the value. Make a note of the number of coins/notes.
This way, you will get the numbers you need.
count = Math.floor(remainder/coinValue) might help you.

Categories