Stop function so price isnt less than -500 Java - java

I've ran into a problem with a method in my program, the task i have been set involves stopping the if statement from running after the balance hits -500, i'v tried if(price < buy && balance > -500) and the current one, while(balance > -500) gives me the result of -594 but the expected result is -495.
although if i take out the {} for the while loop and place a break; right next to the while() it just runs through the junit test which uses a method on the subject class(using observer strategy) to change the price(in this case its setting the price to 0.99 7 times).
From my testing the current solution gives the closest answer, but the part I'm asking for help with is stopping it so it doesn't go over the -500 mark.
'
Thanks in advance and if you want me to add in any more code to help, let me know
#Override
public double getBalance() {
System.out.println("balance " + price);
while(balance > -500)break;
if( price < buy ){
outcome = price * increment;
System.out.println("OUT " + outcome + " ");
}else if(price > sell && portfolio >= 100){
income = price * increment;
}
double total = income - outcome;
balance = balance + total;
}
return balance;
}
edit - ok ive indented it a bit better i hope

I think the problem is that there are no checks if a balance - total will go below -500 before the next iteration begins; simplest way to do this with your current code would be:
double total = income - outcome;
if(balance + total >= -500) {
balance = balance + total;
} else {
break;
}

Related

How to execute a loop until a value hits a number of the users choice

I am working on a project where i have to code a bmi chart, the user inputs a minimum weight and a maximum and the loop should run until the maximum weight. It goes by increments of 5 but im not sure how to make the loop stop at said so maximum weight number. For this example the minimum weight is 120 and the max is 155 so i would need the loop to end at 155 but it goes all the way to 250. So far this is the loop i came up with.
for (int i=0; i<max; i+=5) {
double newWeight = weight + i;
double newBmi = ((newWeight * 703) / (height * height));
String condition = null;
if (newBmi < 18.5) {
condition = "Underweight";
}
else if (newBmi >= 18.5 && newBmi < 25){
condition = "Normal";
}
else if (newBmi >= 25 && newBmi < 30) {
condition = "Overweight";
}
else if (newBmi >= 30) {
condition = "Obese";
}
System.out.println(newWeight + " " + newBmi + " " + condition);
}
and this is the output
WEIGHT BMI CONDITION
120.0 20.595703125 Normal
125.0 21.453857421875 Normal
130.0 22.31201171875 Normal
135.0 23.170166015625 Normal
140.0 24.0283203125 Normal
145.0 24.886474609375 Normal
150.0 25.74462890625 Overweight
155.0 26.602783203125 Overweight
160.0 27.4609375 Overweight
165.0 28.319091796875 Overweight
170.0 29.17724609375 Overweight
175.0 30.035400390625 Obese
180.0 30.8935546875 Obese
185.0 31.751708984375 Obese
190.0 32.60986328125 Obese
195.0 33.468017578125 Obese
and it goes on until 270.. how do i get it to stop at whatever number the user inputs?
Your condition in the loop is not correct because you check that the difference between the current weight is below max, not the calculated weight itself. Therefore the loop runs until the difference is 150, that is for the min weight = 120 it runs until 270 is reached.
So the loop should be rewritten without redundant variable i:
for (double newWeight = weight; newWeight < max; newWeight += 5) {
double newBmi = newWeight * 703 / (height * height);
// the rest of the code
}
Also, formatted output System.out.printf could be used to print the table in a prettier way.

I'm stuck on a Java project, all of the scenarios in my if statements keep getting calculated

I'm working on a point system calculator thing, just learning more about Java and such but I've come into a problem, when I try to put in one of my scenario amounts, it prints every possible scenario in my if statements. Any help would be much appreciated, Thanks!
double basepoints = 0.00;
double spend = 0.00;
double adjpnt = 0.00;
//Prompts the user for their total spend in $, this will calculate the point system.
//In this scenario the customer is incentivised to spend more money at one time due to
// gaining exponentially more points based on spend.
System.out.println("Enter Your Total Spend.");
spend = scan.nextDouble();
basepoints = (spend * 10);
System.out.println("Your base points for this purchase is " + (Math.round(basepoints) )+ ". Calculating the bonuses for this purchase...");
System.out.println("");
if (spend < 20){
adjpnt = (basepoints);
System.out.println("You don't receive any bonuses this time. Sorry that you're poor. You have added " + adjpnt + " points into your account. Have a nice day.");
}if (spend < 50 || (spend > 20)){
adjpnt = (basepoints * 1.25);
System.out.println("We have increased your point gain this purchase by a quarter. " + adjpnt + " points have been added to your account. Have a nice day.");
}if (spend < 100 || (spend > 50));{
adjpnt = (basepoints * 1.5);
System.out.println("Decent purchase. We're gonna throw in a little extra for you, 1.5x the amount of points to be exact. " + adjpnt + " points have been added to your account. Have a nice day.");
}if (spend < 200 || (spend > 100));{
adjpnt = (basepoints * 1.75);
System.out.println("Have 1.75x the extra points on us. " + adjpnt + " points have been added to your account. Have a nice day.");
}if (spend == 69){
System.out.println("nice.");
}
Aside from the mentioned issues with || and missing else, there are some extra ; after if statements which completely ignore any condition.
So, the typos must be fixed and the statements should be simplified using else to define the non-overlapping ranges and select only specific value of adjpnt; nice condition should be checked when appropriate:
System.out.println("Your base points for this purchase is " + (Math.round(basepoints) )+ ". Calculating the bonuses for this purchase...\n");
if (spend < 20) {
adjpnt = basepoints;
} else if (spend < 50) {
adjpnt = basepoints * 1.25;
} else if (spend < 100) {
adjpnt = basepoints * 1.5;
if (spend == 69) {
System.out.println("nice.");
}
} else if (spend < 200) {
adjpnt = basepoints * 1.75;
} else { // this needs to be added to assign bonus correctly
adjpnt = basepoints * 2;
}

Trying to Understand Where My Loop Goes Wrong

So here is my task:
A postal company for a package charges $15 for the first
pound or a fraction thereof and $10 per pound for anything over one
pound. Write a program that prints the charge of a package.
Variables:
weight
First execution:
Weight? -12 Weight must be a positive number.
Second Execution:
Weight? 0 Weight must be a positive number.
Third Execution:
Weight? 2 Pay: $25.00
Forth Execution:
Weight? 2.8 Pay: $33.00
Fifth Execution:
Weight? 2.07 Pay: $25.70
and Here is the code I have developed so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
for (double i = 1; i < weight; i = i + .01) {
if (weight > 1) {
output = output + (1 / 10.00);
}
}
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
Everything works, but what I can't figure out is why (especially in the Fourth and Fifth Execution) is the final output always .10 cents off. Can anyone help me get to the accuracy I need?
Here is what I came up with:
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else {
// Print the charge of the package
if (weight > 1) {
output = cost + ((weight-1) * 10);
} else {
output = cost;
}
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
This should handle all of your cases, as well as numbers between 0 and 1 assuming it's $1 per 0.1 lbs. Instead of your for-loop, you can just use the cost + ((weight-1) * 10) formula. I removed the check to see if weight was equal to 1 because it's handled in the else clause.
If I understand the question correctly, you should never have any fractional dollar amount because anything over a pound is automatically rounded up to the next pound. ie: 2.01 lbs would become 3 lbs. If this is correct, then you could use Math's ceil function to round the weight up to the nearest whole pound, then do something like this:
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double weight;
double cost = 15.00; // set first pound to $15
double output = 0;
System.out.print("Weight?: ");
weight = keyboard.nextDouble();
if (weight <= 0) {
System.out.println("Weight must be a positive number.");
} else if (weight == 1) {
// Print the charge of the package
output = output + cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
} else {
double temp = (Math.ceil(weight)) - 1;
for(double i = temp; i > 0; i-- ) {
output += 10;
}
output += cost;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("Pay: " + money.format(output));
}
}
}
This way, you don't need to bother with 10 cent increments. I hope this helps. Let me know if you have any questions.
This: double i = 1; i < weight; i = i + .01 could be your problem.
Doubles are not exact for decimal math. You're expecting i == weight, at which point the loop should stop, but it might not because i + .01 (however many times) is a tiny fraction less than weight.
My advice is to ditch the loop. If the package is over 1 lb, just subtract one pound from the weight, multiply by the $10 per pound, and then round to the two decimal places you need (NOTE: round it according to how it's spec'd to be rounded, don't just let the conversion from double to decimal do it on its own. There are multiple ways to round something, and decimal does not magically know which one is right for your problem.)
EDIT: Look at your solution, is it supposed to only work to a resolution of 1/10 of a lb? If so, start by rounding the weight. Again, round it according to how it needs to be rounded (down, up, or nearest).

Questions about Nested if Statements for Java

So the question my teacher wrote on the white board is: Input product Name, Quantity, price. Compute the total amount. If total amount is greater than 2000 discount is 5%, if total amount is greater than 5000 discount is 10%, if greater than 10000 discount is 20%
I know that you have to do this kind of format.
if (cost > 2000)
discount = 0.05;
I would put in the correct things before than like
String prodName;
int qty, price;
double cost;
double discount;
I know what I put there is wrong but I think that's how the format of it goes before doing the nested if statement. I really need help on this. I don't need to be given the answers for this because that's spoon-feeding to the max level. I just need some pointers and a guide in order to find out what to do.
First of all you need to read your book thoroughly. Obviously this can be a good start. First learn how if-then works, next if-then-else and finally if-then-else if-then-else. Now lets analyze your question:
Input product Name, Quantity, price. Compute the total amount. If total amount is greater than 2000 discount is 5%, if total amount is greater than 5000 discount is 10%, if greater than 10000 discount is 20%.
Clearly you are going to set one variable, lets call it discount, with checking some condition. For explanation, say if the total amount is greater than 10000, then you are going to set discount = 20%. But careful, when total amount is greater than 10000, it also leads total amount is greater than 5000 or 2000 too! Then are you going to set discount = 10% or discount = 5% respectively? No, you are not.
Hence, to solve your problem, if a higher prioritize condition is already matched, you are not going to check any other conditions. So we will do the following:
discount;
total_amount = some Cost you calculated/inputted
if(total_amount > 10000) {
discount = 0.2;
} else if(total_amount > 5000) {
discount = 0.05;
} else if(total_amount > 2000) {
discount = 0.01;
} else {
discount = 0.00; // no discount for you coz total_amount less than or equal to 2000
}
Now what happens here? If the first test expression is true (total_amount > 10000), it executes the code inside the braces { } just below it and no other block is executed. But if the first test expression is false, it checks the second test expression (total_amount > 5000). If the second test expression is true, it executes the statement/s inside the braces { } just below it and no other block is executed. This process continues. If all the test expression are false, code/s inside else is executed and the control of program jumps below the if-else.
When you fully understand if-else then you can solve this problem in many different ways. Best of luck.
first declare all your variables like you did:
String prodName="";
int qty, price;
double cost; //your cost will be stored here
double discount =0;
Then do your calculations
if (cost > 2000 && cost <= 5000)
discount = 0.05;
else if(cost > 5000 && cost <= 10000){
discount = 0.1;
}else if(cost > 10000){
discount = 0.2;
}
You can do it nested and in the order that the question asks if it will be easier to understand. We just update the discount as necessary. Note that the other answers might be prettier, but this is a way to do it nested:
double cost = ...;
double discount = 0.0;
if (cost > 2000)
{
discount = 0.05;
if (cost > 5000)
{
discount = 0.10;
if (cost > 10000)
{
discount = 0.20;
}
}
}
cost = cost - (cost * discount);
You could do it backwards, or with else if and else statements too.
if (cost > 10000)
discount = 0.2;
else if (cost > 5000)
discount = 0.1;
else if (cost > 2000)
discount = 0.05;
Hope the below code can help you......
if (cost > 10000)
discount = 0.2;
else if (cost > 5000)
discount = 0.1;
else if (cost > 2000)
discount = 0.05;
else
System.out.println("cost is less than 2000 hence no discount applied");
if (cost > 10000)
discount = 0.2;
else if(cost > 5000){
discount = 0.1;
}else if(cost > 2000){
discount = 0.05;
} else {
discount = 0;
}
double total = cost - (cost * discount);
When using if and else ifs if the first if statement is true then that code is executed and none of the other else ifs are checked. If the first if is false then each else if following the if are checked in the order they appear. If one of them is true then that code is executed and none of the others are checked. However, if none are true and you had an else block that code would get executed.
I don't think nested if statements are necessary in this case. Instead you can reverse the order of the if statements so that it first checks for cost > 10000, then cost > 5000, and finally cost > 2000.
Also, if the net amount you mentioned is the cost after discount, then you can do a simple calculation after the if statements. It would look something like this:
double discount = 0;
if (cost > 10000){
discount = 0.2;
}
else if(cost > 5000){
//similar to above, won't spoon-feed this
}
else if(cost > 2000){
//similar to above, won't spoon-feed this
}
double netAmount = cost * (1 - discount);
I know you asked for nested if statements, but you could seriously shorten the solution to this problem using a ternary operator, especially since this is primarily used for assigning a value to discount. Probably considerably more complex than what you were looking for but this could work:
double cost, netAmount;
//get cost
double discount = cost > 10000 ? 0.2 : cost > 5000 ? 0.1 : cost > 2000 ? 0.05 : 0;
netAmount = discount * cost;
Brief Explanation
This works just like nested if statements, but it's a neater, if less readable, way of writing them. Each boolean expression, such as
cost > 10000
is evaluated to either or true or false, as per all boolean expressions. The values after the ternary operator, the ?, are assigned if the expression returns true. Values after the : are assigned if the expression returns false. In this case if cost is greater than 10000, the value 0.2 is assigned. If cost is less than 10000, we want to evaluate another boolean expression so we nest another boolean expression like so:
cost > 10000 ? 0.2 : cost < 5000...
The final : indicates what value will be assigned should all other expression evaluate to false, just like a terminating else statement in an if - else block.
Just a few pointers, you are to compare the price, if you do it in reverse order you could do :
if (cost > 10000)
discount = 0.2;
else if (cost > 5000)
discount = 0.1;
else if (cost > 2000)
discount = 0.05;
This is handy because you aren't nesting if statements and it still is correct.

Storing values not working?

I'm using an array for a project to store currency values, as well as a double variable to hold a running total. When I run my code through the loop, the user input is not stored in the array, and nothing is added to the running total. When the user inputs a -1, it is supposed to break the loop and calculate taxes etc, and when a 0 is inputed, the last value is removed from the array. No matter what I do, I cannot get these values into the array, or the running total to work. I am sure what I am doing wrong is something stupid, but I cannot spot it.
for(i = 0; i < priceArray.length; i++) {
System.out.print("\nEnter the price of the item...");
userInput = input.nextDouble();
if(userInput == -1) { // This will break the user out of the loop.
break;
}
else if(userInput == 0.0) {
System.out.println("You entered a zero, removing last price of $" + priceArray[i] + ".");
i--;
runningTotal =- priceArray[i];
}
else if(userInput > 0.0 && userInput < 2999.99) {
priceArray[i] = userInput;
priceArray[i] += runningTotal;
userInput += runningTotal;
System.out.println("You entered $" + userInput + ", total is $" + runningTotal + ".");
}
else {
i--;
System.out.println("Please enter a valid value under $2999.99.");
}// End if.
};// End for
A couple of things are wrong here
1) When you calculate running total you do it incorrectly (you don't calculate it at all):
priceArray[i] = userInput;
priceArray[i] += runningTotal;
userInput += runningTotal;
It should be this:
priceArray[i] = userInput; /* Save the price */
runningTotal += userInput; /* Increment the total */
Now you will have incremented runningTotal and saved the price correctly.
2) When you remove something (entering 0) you also do it wrong. You print the next empty value, which will be zero and then negate instead of subtracting.
i--; /* Step back one step */
System.out.println("You entered a zero, removing last price of $" + priceArray[i] + ".");
runningTotal -= priceArray[i];
i--; /* The for-loop will increment i for us, so we must subtract one extra time */
In the case where you attempt to remove a value rour running total is going to break. runningTotal =- priceArray[i]; is going to set the value to the negative of the value you are trying to remove. You should use -= instead of =-.
In the case where you attempt to add a value you are also messing up the running total.
priceArray[i] = userInput;
priceArray[i] += runningTotal;
userInput += runningTotal;
I'm not sure what you think is happening on these lines. You set the value of the array at the given index to what was input, which is great. Then you override the value by adding the runningTotal to it, which isn't what you want. Then you are overwriting the input value by adding runningTotal to it, which also isn't what you want. You want to set the value within the array, hten add the value to the runningTotal, and that's it.

Categories

Resources