Questions about Nested if Statements for Java - 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.

Related

Can someone explain what is wrong with my code?

The tax depends on how far apart their salaries are. If the salaries are within $10,000 of each other, the tax is 5% of the total. If they are more than $10,000 apart, the tax is 5% of the larger income plus 3% of the smaller one.
Can someone explain what I'm doing wrong with my if statements that isn't letting the test pass.
public double spouseDistance(double income1, double income2)
{
double tax;
double totalincome = income1 + income2;
double incomedistance = income1 - income2;
if (incomedistance > 10000)
{
if(income1 > income2)
{
tax = income1 * 0.05 + income2 * 0.03;
}else
{
tax = income2 * 0.05 + income1 * 0.03;
}
}
else
{
tax = totalincome * 0.05;
}
return tax;
}
}
#Test
public void testSpousesDistance()
{
TaxCalculator tc = new TaxCalculator();
// The border case here is when the difference between the
// salaries is 10,000 and the value changes at 10,000.01.
// Since the order of the parameters shouldn't matter, do
// both cases with both parameter orders
assertEquals(40000*0.05, tc.spouseDistance(25000,15000), 0.001);
assertEquals(40000*0.05, tc.spouseDistance(15000,25000), 0.001);
assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(20000.00,30000.01), 0.001);
assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(30000.01, 20000.00), 0.001);
}
}
You want to set incomeDistance to Math.abs(income1 - income2) to get the absolute value of the difference. The way you have it, if income2 > income1 you branch to the wrong block of code.
Take your 20,000 and 30,000.01 example. At that point incomeDistance become 20,000-30,000.01, or -10,000, which is less than 10,000.
You have to make sure that the result of the incomedistance is not negative. Because if income 2 is greater than income one, in your code, the result will appear negative.
If the result is negative, multiply the result by (-1) if you don't
want to include an entire library just for a single purpose.

How can I take a value calculated in a if statement and use it outside the if statement?

I would like to know how I can take a calculated value from an if statement and use that value for something else. This is just a portion of my code, the portion that I need help with:
double taxedIncome;
double reducedTax;
int reductionFactor1 = numberSchool;
int reductionFactor2 = numberChildren - numberSchool;
if (income == 10000 && housingCosts > 8000 || income < 10000) {
taxedIncome = income * 0.18;
}
if (housingCosts < 6000 && numberChildren >= 2 && numberSchool >= 1) {
reducedTax = taxedIncome - ((1000 * reductionFactor1) + (500 * reductionFactor2));
System.out.println(reducedTax);
}
As you can see in the first if statement, it says that if income (which is a user entered value) is equal to 10000 and the housing costs (also user entered) is greater than 8000 or if income is less than 10000, then income will be multiplied by 0.18.
taxedIncome = income * 0.18;
However, when I try using the calculated value which is taxed income from the first if statement in the second if statement reducedTax = taxedIncome - ((1000 * reductionFactor1) + (500 * reductionFactor2)); , it gives me the error:
variable taxedIncome might have not been initialized
So my question is, how can I take that calculated value from the first if statement and use it in the second one?
There are a number of ways to do this:
Calculate and save before the if, reuse in the if.
Calculate in a method that can also be called by the if
Use the fact that assignment returns a value
However, the problem you're encountering is specifically that not all paths initialize taxedIncome before it is used.
You're telling the computer that if a certain case is true then taxedIncome = income * 0.18; It's asking, "ok, so what should it be if it's not?"
If that answer isn't exactly the same consider adding an else to your first if. If you'd put a default value here consider setting taxedIncome to the default value at the start.
It's good practice to initialize your variables as you declare them. Typically, you'd want to initialize numbers to zero.
In your case, it's possible that your if statement may not execute so taxedIncome may never have been assigned a value
double taxedIncome = 0; // Initialize to zero or some default value
double reducedTax = 0; // Initialize to zero or some default value
int reductionFactor1 = numberSchool;
int reductionFactor2 = numberChildren - numberSchool;
if (income == 10000 && housingCosts > 8000 || income < 10000) {
taxedIncome = income * 0.18;
} else {
// If you initialized taxedIncome to zero you may want to default it to some other value if you if statement results in false.
// taxedIncome = ???
}
if (housingCosts < 6000 && numberChildren >= 2 && numberSchool >= 1) {
reducedTax = taxedIncome - ((1000 * reductionFactor1) + (500 * reductionFactor2));
System.out.println(reducedTax);
}

Stop function so price isnt less than -500 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;
}

Save values while inside a for loop

So I have the following code
for (int i = 0; i <= numberOfTickets; i++)
{
System.out.println("Please enter your age or if you are a student enter -1");
int age = input.nextInt();
if ((age < 10) && (age > 0))
{
cost = (cost / 4);
}
else if ((age < 16) && (age >= 10))
{
cost = (cost / 2);
}
else if (age > 60)
{
cost = (cost / 2.5);
}
else if (age == -1)
{
cost = (cost / (4/3));
}
System.out.println(cost);
}
the problem is say that initially the cost is £10 and the user enters an age of 12 I want the value of £5 to be saved as say int ticketCost1 before continuing the for loop but starting with 10 again.
In essence i want to at the end of the loop have all the costs of the tickets with the individual discounts applied and to be then able to dd them all together and have a final cost.
P.S. I intend to add more so that for every child i.e. age 0 to 10 then they go free with anyone over the age of 16.
In java.
Make a new double, for now lets call it sum. Now instead of writing:
cost = (cost/whatever);
do this:
sum+= (cost/whatever);
now you save all them in 1 number summed, and cost stays as 10; while all the discounts are applied. Just make sure you initialize sum to 0 OUTSIDE and before the for loop
If I understand you correctly, you have a group of people of varying ages, and you want to find the total cost of all the tickets purchased by the group. You can have two lists, then: one to store the ages, and one to store the ticket costs. The cost of the group will be the total cost stored in the second list.
static final TICKET_PRICE = 10;
int getTotalCost(List<Integer> ages) { // populated list of ages
List<Integer> costs = new ArrayList<>();
for (int i : ages)
costs.add(getTicketPrice(int age));
int totalCost = 0;
for (int curr_cost : costs)
totalCost += curr_cost;
return totalCost;
}
int getTicketPrice(int age) {
int price;
if (age > 60) price = TICKET_PRICE/2.5;
... // all the other conditions, e.g. for students, children under 10, etc.
else price = TICKET_PRICE; // if no special condition applies
return price;
}
For the more complicated conditions (e.g. a child under 10 goes free with another person over the age of 16), it's best if you have a separate method to compute the total cost. Keep in mind that as you increase these conditions that depend not just on the individual, but on the age-distribution of the whole group, the optimal cost computation will start to resemble quite a complex problem in and of itself.

IF statement that is greater than and less than specific numbers

I have a project where I have to create a tax application. I have two integers: gross and taxrate. When the user inputs his gross income, I want it to multiply the certain percentage of the tax rate in his bracket for the tax due. My code is the following:
if (gross < 9075) {
taxrate = (int) (gross * .10);
}
else (gross > 9075 && < 36900) {
taxrate = (int) (gross * .15);
}
It tells me there is an error, so I assume I am messing up somewhere. Is there a way to create a proper if statement that goes between two numbers?
You must explicitly state both operands to any binary operator, including comparison operators. Try
} else if (gross > 9075 && gross < 36900) {
Incidentally you may need to consider the case of exactly 9075, either with
if (gross <= 9075){
OR
} else if (gross >= 9075 && < 36900) {
It looks like you are using a conditional with the else statement, and not using your operators correctly. You want to change this to
else if (gross > 9075 && gross < 36900)
Notice I have changed else to else if and changed the conditional to have the comparisons done correctly.
Try giving it as
taxrate = (int) (gross*0.10f);
and
taxrate = (int) (gross*0.15f);

Categories

Resources