Not getting desired output from Jframe - java

I'm new to programming GUI in Java. My code is simple and only needs to do some basic arithmetic but for some reason it's not working. I don't know that I'm using the String.valueOf()correctly.
My code:
String restaurantName;
double subTotal = 0;
int tipPercentage = 0;
double totalBill = 0;
double tipInDollars = 0;
restaurantName = txtRestaurantName.getText();
subTotal = Double.parseDouble(txtSubtotal.getText());
tipPercentage = Integer.parseInt(txtTipAmt.getText());
tipInDollars = ((tipPercentage / 100) * subTotal);
totalBill = (tipInDollars + subTotal);
lblDisplayTip.setText(String.valueOf(tipPercentage) + "%");
lblDisplayTotalBill.setText(String.valueOf(totalBill));
If the user enters 50 for subtotal and 10 for the tip percentage, I would expect tipInDollars to equal 5 and for totalBill to equal 55.
Yet the output is:

Your issue is not with your display, it's with your calculation, or rather, the variables you use for your calculation. You can either make tipPercentage a double, or you can make the 100 in this line: tipInDollars = ((tipPercentage / 100) * subTotal); into 100.0. Either solution should fix your problem.
The problem arises from dividing an integer (tipPercentage) by another integer (100). When you do this, Java will round down and always make your result 0.

Related

I need help making change in java. It doesnt give out change correctly

Hi I'm trying to make a method that gives you change in Hundreds, Fifties, Twenties, Tens, Fives, ones as well as quarters dimes and nickels. the user gives input and its supposed to look something like this: 6.87 1 five 1 one 3 quarters 1 dime 2 pennies
So far I have this as my code:
import java.util.Scanner;
/**
*
* #author Cjespinomartine
*/
public class Assignment04 {
public static void main(String[]args) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter your amount");
double amount = stdin.nextDouble();
double remainder = Math.round(amount * 100);
double hundreds = remainder / 1000;
remainder = remainder / 1000;
double fifties = remainder / 500;
remainder = remainder / 500;
double twenties = remainder / 200;
remainder = remainder % 200;
/*
double fives = remainder / 5;
remainder = remainder % 5;
double ones = remainder / 1;
remainder = remainder % 1;
double quarters = remainder / .25;
remainder = remainder % .25;
double dimes = remainder / .10;
remainder = remainder %10;
double nickels = remainder / .5;
remainder = remainder % .5;
double pennies = remainder;
*/
System.out.println(hundreds + "hundred/s");
System.out.println(fifties + "fiftie/s");
System.out.println(twenties + "twentie/s");
/* System.out.println(fives + "five/s");
System.out.println(ones + "one/s");
System.out.println(quarters + "quarter/s");
System.out.println(dimes + "dime/s");
System.out.println(nickels + "nickel/s");
System.out.println(pennies + "cent/s");
*/
}
}
It doesn't give out change in order it just gives out hundreds. I commented some of the change because I'm trying to get the math right. I think the assignment required if and else if so if it does can you help me out with where I put it. any help will mean a lot i'm very stuck thank you.
There are a few things wrong.
The first issue is your initial handling of remainder – you're multiplying by 100, so if input is 1274.56, you end up with 127456 (ignoring floating point problems which are valid but I'll stay focused on this first point). The output of Math.round() is either an int or long, but definitely not a double so you're adding confusion for yourself by storing it as a double – instead, store the result as long. From there, when you calculate hundreds, you need to divide by 10,000 not 1,000. Also, store that as an int, not a double. Here's what that would look like:
long remainder = Math.round(1274.56 * 100);
int hundreds = (int) remainder / 10000;
System.out.println("hundreds: " + hundreds);
The above prints out "12" for hundreds, which is what you want.
The second issue is how you're calculating remainder. You want everything that's "left over" from the prior calculation which you do by using % (modulus operator), and also use 10,000 instead of 1,000. For the hundreds case, it would be this:
remainder = remainder % 10000;
System.out.println("remainder: " + remainder);
The above code would print this:
remainder: 7456
This should give you enough to get the rest of your math working properly.
remainder = remainder / 1000; is wrong. What you want is the remainder after you've taken out all the hundreds. remainder = remainder % 1000; -looks like the commented out ones are correct...
Also don't use floating point types for money. Google will give you a thousand reasons why.

trouble using modulus for cash register program

For my cash register simulation, I have to take the change due and print it out in terms of 100s, 50s, 20s, 10s, 5s, 1s, and ofcourse change. I have two questions that I'm struggling with:
1.) Is there an easier way to figure out how many dollar bills are needed for each one if any? My equations work but it' s long and I think there's an easier way to do it?
2.) When dealing with cents is am i supposed to do (changeDue%100)?
changeDue is equal to 39.12 and I'm trying to pull of just the 12 cents, but I dont quite know how? Can someone please help explain to me?
double changeDue = 39.12;
double coins;
double change;
int hundreds;
int fifties;
int twenties;
int tens;
int fives;
int ones;
int quarters;
int dimes;
int nickels;
int pennies;
double cents;
//calculations for amount of each dollar bill that needs to be given back
hundreds = (int)(changeDue/100);
change = changeDue - (hundreds * 100);
fifties = (int)(change/50);
change = changeDue - (hundreds * 100) - (fifties * 50);
twenties = (int)(change/20);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20);
tens = (int)(change/10);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20) - (tens * 10);
fives = (int)(change/5);
change = changeDue - (hundreds * 100) - (fifties * 50) - (twenties * 20) - (tens * 10) - ( fives * 5);
ones = (int)(change/1);
//calculations for amount of coins that needs to be given back
cents = changeDue%100;
quarters = (int)cents/10;
The modulus operator gives the remainder after division. In your example changeDue % 100 divides the number by 100 and returns the remainder. If you provide the number in pennies, say 3912, then this will work exactly as you expect. However, you are using dollars instead. So first convert the dollar amount to pennies by multiplying by 100.
Note
ones = (int)(change/1); can be simplified to ones = (int) change;.
Another method to derive change less than a dollar is:
cents=changeDue-(int)changeDue
1.) Is there an easier way to figure out how many dollar bills are needed for each one if any? My equations work but it' s long and I think there's an easier way to do it?
I have found an easier way for your calculations. Refer to the code and code comments below.
public static void main(String args[]) {
double changeDue = 39.12; // The change needed
double change = changeDue; // Used for the calculations of change
/*
* Add here possible change, use an array so that you won't have to declare many
* variables This way if you want to add other possible changes you just have to
* add it in the array But make sure the possible changes is arrange in
* descending order
*/
double[] possibleChange = new double[] { 100, 50, 20, 10, 5, 1, 0.25, 0.10, 0.05, 0.01 }; // the possible changes
String[] possibleChangeLabel = new String[] { "Hundreds", "Fifties", "Twenties", "Tens", "Fives", "Ones", "Quarters", "Dimes", "Nickels", "Pennies" }; // used for printing
int[] coins = new int[possibleChange.length]; // Used for the number of coins needed for each possible change
/*
* Loop through all the possible changes and acquire the possible number of
* coins needed for each change
*/
for (int i = 0; i < possibleChange.length; i++) {
coins[i] = (int) (change / possibleChange[i]); // calculate the possible number of coins in the given change
change = (double) Math.round((change - (coins[i] * possibleChange[i])) * 100) / 100; // Update the change and limit to 2 decimal places
}
/*
* This is for printing
*/
System.out.println("Your change is $" + changeDue);
System.out.println("The change is composed of: ");
for (int i = 0; i < possibleChange.length; i++) {
if (coins[i] > 0) {
System.out.println( "\t" + coins[i] + " piece/s of $" + possibleChange[i] + "(" + possibleChangeLabel[i] + ")");
}
}
}
2.) When dealing with cents is am i supposed to do (changeDue%100)? changeDue is equal to 39.12 and I'm trying to pull of just the 12 cents, but I dont quite know how? Can someone please help explain to me?
I don't know why you are needing this process, but you can try my code below.
double number = 123.45; // Your change
int decimal = (int) number; // You will get the whole number part (123)
double fractional = number - decimal; // You will get the fraction part (45)

Total of percentages is not correct

I am distributing tokens but they are not all distributed. I have multiple percentages and get the amount of tokens to give for that percentage but they do not equal up to the total.
Example:
int tokens = 50;
double[] percentages = new double[] {0.3725, 0.219, 0.115, 0.2935};
int total = 0;
for(double d : percentages){
int amount = (int) (tokens * d);
total += amount;
}
The total is 47 though. I have also tried to round it with Math.round
for(double d : percentages){
double rounded = Math.round(d * 100);
int amount = (int) (tokens * (rounded / 100));
total += amount;
}
The total is 49
I can never seem to get 50, it is always below or above. I want to distribute these tokens are evenly as possible. If you can help please do!!
Use double total. Using int leads to loss of decimal information
double total = 0;
for(double d : percentages){
double amount = (tokens * d);
total += amount;
}
What you should do is round down the percentages as you were originally (casting to int). Then look at how many tokens you have left over. These should be distributed to the cases that are furthest away from their true value.
In each case the error would be:
double error = (percentage * tokens) - (int)(percentage * tokens);
Sort your cases by error, and award the tokens to the cases with the largest error until you have given out all 50.
I'm not sure why this works but I changed the total code to
total += income/1.025;
I think it works because while the loop doesn't display the age for 68 it still runs through one last time. So you'd have to undo the rate for retirement.

How can I turn this compound value function into a for-loop?

Okay so I am new to Java. I have a program that calculates the compound value after asking the user for a savings amount and an annual interest rate. I'm having trouble getting it into a for loop but I feel like I'm somewhat close? The hard part in my mind is understanding how to get the last months total into the new calculation.
Here's my formula for the compound value currently:
firstMonth = savingAmount * (1 + monthlyInterestRate);
secondMonth = (savingAmount + firstMonth) * (1 + monthlyInterestRate);
thirdMonth = (savingAmount + secondMonth) * (1 + monthlyInterestRate);
fourthMonth = (savingAmount + thirdMonth) * (1 + monthlyInterestRate);
fifthMonth = (savingAmount + fourthMonth) * (1 + monthlyInterestRate);
sixthMonth = (savingAmount + fifthMonth) * (1 + monthlyInterestRate);
It is ugly obviously and it should be in a for-loop. Again the savingAmount is user input and the annualInterestRate is user input. The the monthlyInterestRate is annualInterestRate/12.
Here is the for-loop I have so far.
for (int i = 1; i <= 6; i++ );
{
sixthMonth = savingAmount * Math.pow(1+monthlyInterestRate, 6);
}
I am still learning for-loops but doesn't my code say it adds up while it is less than or equal to 6? And while those are true to do the formula I provided. No you don't have to answer the question but if you could lead me in the right direction that'd be great. So how would I start to convert it? Feel free to ask for more info if needed.
Try this:
for (int i = 1; i <= 6; i++) {
monthAmount = (savingAmount + monthAmount) * (1 + monthlyInterestRate);
}
This should get you to the same answer.
You were on the right track, but this will allow you to use the previous months amount in the formula. This code will also work for however long you want the loop to run for.
I would actually recommend using the compound interest formula A = P (1 + r/n) ^ nt.
A - final amount with compound growth
P - principal investment
r - annual interest rate
n - number of times the interest is compounded per time period
t - number of time periods compounded
So you could then reduce all of this to:
amount = savingAmount * Math.pow(1 + monthlyInterestRate/timesCompoundedPerMonth,
timesCompoundedPerMonth * monthsCompounded);
Compound Interest Formula - Explained
I would recommending storing the amounts in a list for easy lookup if you want to see how much savings you will have at each month.
public static void main(String args[]) {
double savingsAmount = 543.23;
double annualInterestRate = 0.85; // %
double monthlyInterestRate = annualInterestRate / 12;
List<Double> savings = new ArrayList<Double>();
savings.add(savingsAmount); // month 0
int monthsInTheFuture = 6;
double compoundInterest = 1 + monthlyInterestRate;
for (int i = 1; i <= monthsInTheFuture; i++) {
double previousSavings = savings.get(i-1);
double nextSavings = previousSavings * compoundInterest;
savings.add(nextSavings);
}
System.out.println(savings);
}

Calculate a value to update JProgressBar

I would like to display the proportion of an initial value in a JProgressBar.
private void updateProgressBars() { //Update the progress bars to the new values.
int p1 = 0, p2 = 1; //Player numbers
double p1Progress = (intPlayer1Tickets/intInitialPlayer1Tickets) * 100;
double p2Progress = (intPlayer2Tickets/intInitialPlayer2Tickets) * 100;
progressbarPlayerTickets[p1].setValue((int) p1Progress);
progressbarPlayerTickets[p1].setString("Tickets left: " + Integer.toString(intPlayer1Tickets));
progressbarPlayerTickets[p2].setValue((int) p2Progress);
progressbarPlayerTickets[p2].setString("Tickets left: " + Integer.toString(intPlayer2Tickets));
}
In this code, the intention was to calculate the percentage of the amount of tickets left a player has. intInitialPlayer1Tickets and intInitialPlayer2Tickets were both set to 50. intPlayer1Tickets and intPlayer2Tickets were then set to their respective initial tickets value (i.e. both set to 50 as well). When I subtract any number from intPlayer1Tickets or intPlayer2Tickets (e.g. intPlayer1Tickets = 49, intInitialPlayer1Tickets = 50), their respective progress bars' value would be set to 0, which is not my intention. Both progress bars have their min and max values set to 0 and 100.
So how would I make it so it would reflect the proportion of tickets left as a percentage?
You are doing integer math and then converting it to a double. In integer math when you divide a number with a number that is bigger, the answer is always 0.
You want to get Java to do your math with floating point numbers rather than with integers. The easiest way to do this is to make your divisor a double.
When you run this code
public class Numbers{
public static void main(String []args){
int five = 5;
int ten = 10;
System.out.println(five/ten);
System.out.println(five/(double)ten);
System.out.println((five/(double)ten)*100);
}
}
You get this as the output
0
0.5
50.0
So, to answer your question what you want is something like this
double p1Progress = (intPlayer1Tickets/(double)intInitialPlayer1Tickets) * 100;
But you'd be just fine using float for this instead of doubles.
Cast the value of intPlayer1Tickets, intPlayer2Tickets, intInitialPlayer1Tickets and intInitialPlayer2Tickets to double before you calculate. As in:
double p1Progress = (((double) intPlayer1Tickets)/((double) intInitialPlayer1Tickets)) * 100;
double p2Progress = (((double) intPlayer2Tickets)/((double) intInitialPlayer2Tickets)) * 100;

Categories