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);
Related
I'm creating a method to let the user know how much money would have been saved if they decide to switch to another package.
public static String savingsCalc(char pack, double hours)
{
String returnVal = "";
double packageRateA = 9.95;
double packageRateB = 13.95;
double packageRateC = 19.95;
double savings = 0;
if (hours > 10) packageRateA = 9.95 + ((hours - 10) * 2.00);
if (hours > 20) packageRateB = 13.95 + ((hours - 20) * 1.00);
if (pack == 'A')
{
if (packageRateA < packageRateB) returnVal = "";
else if (packageRateA < packageRateC && packageRateA > packageRateB)
{
savings = packageRateA - packageRateB;
System.out.printf("You would save $%.2f if you switched to package B!%n", savings);
}
else if (packageRateA > packageRateC)
{
savings = packageRateA - packageRateC;
System.out.printf("You would save $%.2f if you switched to package C!%n", savings);
}
}
return returnVal;
}//shows savings if changing to other package
If I enter "15" hours, it should print savings for "Package B" but does not, I checked that all the values are correct by printing the line, but I don't understand why it won't print.
packageRateA becomes 19.95 because hours > 10. packageRateB stays at 13.95. packageRateC stays at 19.95.
Is this true?
packageRateA < packageRateB
No, A is greater.
Is this true?
packageRateA < packageRateC && packageRateA > packageRateB
No, A and C are the same.
Is this true?
packageRateA > packageRateC
No, A and C are the same.
So none of the conditions are true and returnVal remains empty.
This happens because you are checking packageRateA < packageRateC.
Which doesn't get satisfied when you pass the argument.
packageRateA would be 19.95 when hours=15.00 which is equal to packageRateC.
If you change the condition to packageRateA <= packageRateC your code would work.
Check your logic. If I assume the value passed in for pack is A, then the following line changes packageRateA to 19.95:
if (hours > 10) packageRateA = 9.95 + ((hours - 10) * 2.00);
After that line, packageRateA is the same value as packageRateC and more than packageRateB.
None of the conditional statements evaluate to true with those values.
If you want it to select packageRateB, you need to change the logic in this conditional
else if (packageRateA < packageRateC && packageRateA > packageRateB)
I'm still studying java and I'm doing an exercise on this converter. I wrote something as following, it works. A miner problem is when it converts small decimal fraction, it will have the usual precision problem (I understand that, so i make it prints out the fraction it actually used for calculation). I found that most of the online or app converters are dealing this problem using one of the following way:
limit the decimal space from user's input and their output
output the inaccurate result as is
I want to know how people think about this problem when using a converter with slightly precision problem..does it matter at all? And is there anyway to fix this problem really? Please share your thoughts. Thanks ^^
private static void DtoB() {
int power;
long i, integer;
double d, fraction, f;
System.out.println();
System.out.print("Plese enter the denary number: ");
//Break the number
d = getDouble(); //method that gets the valid input form user
integer = Math.abs((long)d);
fraction = Math.abs(d - integer);
i = integer; //store the original input for later use
f = fraction; //store the original input for later use
power = 1;
System.out.println("Integer part: "+i);
System.out.println("Fraction part: "+f);
System.out.println();
System.out.print("The binary form is: ");
//Convert the integer part
//get the largest power of 2 smaller than the number
while(integer != 0) {
while(power <= integer/2) {
power *= 2;
}
System.out.print("1");
integer -= power;
//get the rest 1 & 0 till the smallest power of 2
while(power > 1) {
power /= 2;
if (integer < power)
System.out.print("0");
else {
System.out.print("1");
integer -= power;
}
}
}
//Convert the fraction part
if (fraction < 1.0){ //check if there is a fraction part needs to convert
System.out.print(".");
while (fraction < 1.0 && fraction != 0) {
fraction *= 2;
if (fraction > 1.0) {
System.out.print("1");
fraction = (fraction - 1);
}
else {
System.out.print("0");
}
}
}
else if (fraction == 0) {
}
System.out.println();
}
You own the requirement, so it's up to you what's acceptable. If you were writing this for a customer, of course you would ask them.
To avoid problems with floating-point precision, avoid floating-point types altogether.
The BigDecimal class exists for doing arbitrary-precision maths in Java.
If, for reasons of study, you don't want to use BigDecimal, then you could write similar functionality yourself. Read in your number as a String. Split it on the . to get an integer part and a fractional part, and convert these to integers.
You'll also need to keep track of the leading zeros in the fractional part - otherwise 3.51 and 3.00051 would evaluate to the same thing. So, for example:
3.51 parses to i==3, f==51, z==0
42.0022 parses to i=42, f==22, z==2
The conversion to binary, I leave up to you as an exercise.
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.
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);
}
I have done a google around but can't get my head around what's wrong with my code here.
I'm getting an Illegal start of expression error in the if statement at the first 'Else if'
I'm pretty new to Java but trying to quickly learn as its a requirement of my computing course I'm hoping to do.
Any help greatly appreciated.
import java.util.Scanner;
public class net_salary{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int income;
int incometax;
int afterincometax;
int nationalinsurance;
int afterni;
int pension;
income = in.nextInt();
if(income = 0) {
incometax = 0;
} else if (income >=9000 & <=21000) {
incometax = income * 0.15;
} else if (income >=21000 & <=31000) {
incometax = income * 0.2;
} else if (income >=31000 & <=50000) {
incometax = income * 0.225
You need else if (income >=9000 && income <=21000) instead of else if (income >=9000 & <=21000).
Similarly for the other else if expressions.
You have to make two separate comparisons to income. You can't say "if income is greater than or equal to 9000 or less than or equal to 21000". You must say "if income is greater than 9000 or income is less than or equal to 21000".
& is a bitwise AND. && is logical AND.
As stated by others, income = 0 should read income == 0.
You need && not &, and repeat the variable 'income' :
else if (income >=9000 && income <=21000)
You are also using = where you probably mean ==
if(income == 0)
= assigns a value, == tests whether two values are equal.
Your if/else if block expression always should results as boolean (either true/false). In Java, && represents AND, & is bitwise operator which manipulates bits.
if(income == 0)
{
incometax = 0;
}
**else if (income >=9000 && income <=21000)**
{
incometax = income * 0.15;
}
else if (income >=21000 && income <=31000)
{
incometax = income * 0.2;
}
else if (income >=31000 && income <=50000)
{
incometax = income * 0.225
if(income = 0)
should be
if(income == 0)
and
else if (income >=9000 & <=21000)
(and it's followers) should be
else if (income >=9000 && income <=21000)
and looks like you you need to make some of your variables double instead of int.
Check the usage of "=", "==", "&", "&&" operators in Java.
public class net_salary{
public static void main(String[]args){
int income, ncometax, afterincometax, nationalinsurance, afterni, pension;
Scanner in = new Scanner(System.in);
income = in.nextInt();
if(income == 0) {
incometax = 0;
} else if (income >= 9000 && income <= 21000) {
incometax = income * 0.15;
} else if (income >=21000 && income <= 31000) {
incometax = income * 0.2;
} else if (income >=31000 && income <= 50000) {
}
}
}