Variable not updating based on a change of another - java

In my program I have a method calculateCost(), which gets the cost of a truck based on the minimum temperature of said truck.
public double calculateCost() {
int minimumTemperature = this.getTemperature();
System.out.println("Temp is: " + minimumTemperature);
double costOfTruck = 900 + 200 * (Math.pow(0.7, (minimumTemperature / 5)));
System.out.println("Cost is: " + costOfTruck);
return costOfTruck;
}
When this method is executed, the minimumTemperature correctly changes as shown in the console, however, the costOfTruck doesn't change when the minimumTemperature is changed.

If minimumTemperature < 5 then minimumTemperature / 5 will equal zero due to integer division and Math.pow(0.7, (minimumTemperature / 5) will equal 1, so try using a double numeric type
double costOfTruck = 900 + 200 * (Math.pow(0.7, (minimumTemperature / 5.0)));

Related

Splitting units base of a number and separating remainders

I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!

Java - Else If loop will NOT work with instance variable

I'm attempting to calculate how much tax a user should pay, based on wage. For example, calculating 20% in the first if loop, this will be saved in generaltax:
int generalTax = 0;
int userGrossPay = 50000;
if (userGrossPay <= 10600) {generalTax += 0;}
else if (((userGrossPay >= 10600) && (userGrossPay <= 31785))) { generalTax = ((20/100) * userGrossPay); }
else if (((userGrossPay >= 31786) && (userGrossPay <= 150000))) { generalTax = ((40/100) * userGrossPay); System.out.println(generalTax);}
else if (userGrossPay > 150001) {generalTax = ((45/100) * userGrossPay); }
else{System.out.println("error");};
userGrossPay -= generalTax;
System.out.println(userGrossPay);
However generalTax pay is for some reason always stuck as 0 and is not properly updating on each iteration.
Your problem is that you are always adding 0 or assigning 0 to generalTax.
For example, (20/100) * userGrossPay is 0, since 20/100 is 0 due to int division. Change it too 0.2 * userGrossPay or 20.0/100 * userGrossPay. Similarly change all other places where you divide two integers.
This is caused by integer division.
If you mix floating data type with integer, it will give you a data conversion by promotion.
For example:
int num = 5;
System.out.println(num / 2); //Gives you 2
System.out.println(num / 2.0); //Gives you 2.5
System.out.println(num * 2); //Gives you 10
System.out.println(num * 2.0); //Gives you 10.0
System.out.println(num + 2.5); //Gives you 7.5
If all operands in the operation are integers, your output will be integer as well. This is how you got into an integer division accidentally.
((20/100) * userGrossPay);
I see that you already accepted Eran's answer and understood what went wrong, I am here to give you some additional information.

How to get a percentage from an array value

I am trying to get a percentage from an array value in a for-loop.
System.out.println(playerName[i+1] + " got " + playerScore[i] + " questions right out of " + question.length + "!\n");
double playerScorePercentage = (playerScore[i] / question.length) * 100;
System.out.println("Which is " + playerScorePercentage + "%!");
What am I doing wrong? The playerScoredisplays a value but when I am trying to do a calculation with it below, it displays 0.0 no matter what.
An example run:
John got 3 questions right out of 10!
Which is 0.0%!
Try casting the values before the division:
double playerScorePercentage = ((double)playerScore[i] / (double)question.length) * 100;
And search the web for "integer division" if you don't know the topic.

Dynamically calculating change to the nearest 10 dollars

I am new to Java and I'm trying to figure out how to dynamically calculate the change to the nearest 10 dollars. For instance, the user inputs a value (34.36), my code then calculates tip, tax, and total amount for the bill (total 44.24). Without user input, I need to calculate the change from $50.00. I've tried to round up to 50.00 from 44.24 with no luck, obviously I am doing something wrong. I've tried Math.round and tried to find the remainder using %. Any help on how to get the total change due to the nearest 10 dollar value would be great. Thank you in advance, below is my code:
Full dis-closer, this is a homework project.
import java.util.Scanner;
import java.text.NumberFormat;
import java.lang.Math.*;
public class test1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//Get input from user
System.out.println("Enter Bill Value: ");
double x = sc.nextDouble();
//Calculate the total bill
double salesTax = .0875;
double tipPercent = .2;
double taxTotal = (x * salesTax);
double tipTotal = (x * tipPercent);
double totalWithTax = (x + taxTotal);
double totalWithTaxAndTip = (x + taxTotal + tipTotal);
//TODO: Test Case 34.36...returns amount due to lower 10 number
//This is where I am getting stuck
double totalChange = (totalWithTaxAndTip % 10);
//Format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
//Build Message / screen output
String message =
"Bill Value: " + currency.format(x) + "\n" +
"Tax Total: " + currency.format(taxTotal) + "\n" +
"Total with Tax: " + currency.format(totalWithTax) + "\n" +
"20 Percent Tip: " + currency.format(tipTotal) + "\n" +
"Total with Tax and 20 Percent Tip: " + currency.format(totalWithTaxAndTip) + "\n" +
"Total Change: " + currency.format(totalChange) + "\n";
System.out.println(message);
}
}
you make
double totalChange = round((totalWithTaxAndTip / 10)) * 10;
Math.round rounds a number to the nearest whole number, so as others have shown, you need to divide by 10, then multiply by 10 after rounding:
double totalChange = tenderedAmount - totalWithTaxAndTip;
double totalChangeRounded = 10 * Math.round(totalChange / 10);
Math.ceil(double) will round up a number. So what you need is something like that:
double totalChange = (int) Math.ceil(totalWithTaxAndTip / 10) * 10;
For totalWithTaxAndTip = 44.24, totalChange = 50.00
For totalWithTaxAndTip = 40.00, totalChange = 40.00
Everyone, thank you very much for helping me. I tested out everyone's solution. This is my final working code.....
double totalAmountPaid = totalWithTaxAndTip - (totalWithTaxAndTip % 10) + 10;
I tested it out using many different values and it seems to be working the way I want it to.
Again, I appreciate everyone for taking the time to help me out.

Math line only running once in a loop

this is my first interaction with this site, I have heard good things and I hope I can find the answer that I am looking for. I am learning Java and using the Eclipse IDE in a computer science class at my high school and I came across a problem that neither my teacher or I can solve. Here are the instructions.
"The German Mathematician GottfriedLeibniz developed the follow method to approximate the value of π.
π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
Write a program that allows the user to specify the number if iterations used in this approximation and displays the resulting value."
Now the code.
import java.util.Scanner;
public class GottfriedLeibnizPi {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter how many iterations you want to go to: ");
int iterations = reader.nextInt();
double pi = 0;
if (iterations >= 0) {
for (int count = 0; count <= iterations - 1; count++) {
System.out.println("pi: " + pi + " count: " + count); //debug statement to show pi and count before running the code
if (count % 2 == 0) {
pi = pi + (1 / (1 + (2 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n)
} else {
pi = pi - (1 / (1 + (2 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n)
}
System.out.println("pi: " + pi + " count: " + count + "\n"); //debug statement to show pi and count after running the code
}
pi = pi * 4; //obtains the true value of pi
System.out.println("The value of pi after " + iterations + " iterations is " + pi);
} else {
System.out.println("Please enter a non-negative number");
}
}
}
Here is the output with the the debugging statements if I enter five at the prompt.
Enter how many iterations you want to go to: 5
pi: 0.0 count: 0
pi: 1.0 count: 0
pi: 1.0 count: 1
pi: 1.0 count: 1
pi: 1.0 count: 2
pi: 1.0 count: 2
pi: 1.0 count: 3
pi: 1.0 count: 3
pi: 1.0 count: 4
pi: 1.0 count: 4
The value of pi after 5 iterations is 4.0
My math says that answer should be 3.3396... but the math in my loop does not appear to run more than once. I have not found anything on here that is close to my problem, does anyone know what is wrong?
The problem seems to be a roundoff caused by integer division. Try replacing the relevant part of your code with this:
if(count % 2 == 0){
pi = pi + (1 / (1 + (2.0 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n)
}
else{
pi = pi - (1 / (1 + (2.0 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n)
}
Since "1" in the numerator is an integer, and "(1 + (2*Count))" in the denominator is also an integer, you will get integer division which truncates any remainder from the division. Since the denominator in this case is going to be greater than or equal to 1, 1/(positive integer greater than 1) will always result in 0 in integer division. By adding a decimal to one of the integers Java will treat it as a double and not perform integer division.
So actually, there is no problem with the execution of the lines. When I run the code with the above changes I get the same answer as given by your teacher.
The value of pi after 5 iterations is 3.3396825396825403
int/int gives an int type, by which you loose the fractional part of the divison ( 3/2 gives 1 ) . So you need -
pi = pi + (1.0 / (1.0 + (2 * count))); // Notice the 1.0
Similarly in the other case too.
In both the cases of:
pi = pi + (1 / (1 + (2 * count))); // (1 / (1 + (2 * count))) everything here is an int so, so you are losing . and everything after .
change it to
pi = pi + (1d / (1 + (2 * count)));
iterations=int(input('enter no of iterations'))
adding = 0
for i in range(1, iterations + 1, 2):
if i % 4 == 1:
adding += 1/i
else:
adding -= 1/i
pi = 4 * adding

Categories