Java illegal start of expression - java

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) {
}
}
}

Related

Java BMI program

The first part of the code is working, the program takes inputs as height and weight as displays an output message. When I press n I can go to the second part and take inputs for height in inches and the weight in pounds. As soon as I take them the program outputs the resulting bmi is: Nan. and the variable bmi might not have been initialized. i want to convert the height and weight from inches and pounds to meters and then show the resulting bmi This is my code:
package uly14th;
import java.util.Scanner;
public class BmiCalculator {
private static float BMI2;
public static void main(String[] args) {
char Y;
char y;
char Q;
char n;
char N;
float heightInMeters, weightInKilograms, BMI;
float heightInInches, weightInpounds;
float heightInMeters2 = 0, weightInKilograms2 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please state whether you are going to use kilograms & meters or, inches & pounds");
System.out.println("If you want to use the former please press Y or if you want to use the latter please press N");
Q = input.next().charAt(0);
if(Q == 'y' || Q == 'Y' ) {
System.out.println("Please enter the height in meters: ");
heightInMeters = input.nextFloat();
System.out.println(" and weight in kilograms: ");
weightInKilograms = input.nextFloat();
BMI = weightInKilograms / (heightInMeters * heightInMeters);
System.out.println("The resulting BMI of the person is: " +BMI);
if (BMI < 18.5){
System.out.println("The personis underweight");
}
else if ((BMI<=25.0) && (BMI >= 18.5)){
System.out.println("The person is normal");
}
else if ((BMI >= 25.0) && (BMI <=30.0 )){
System.out.println("The personis obese");
}
else if(BMI>=30.0) {
System.out.println("The person is obese and should exercise");
}
}
if ((Q == 'n') || (Q == 'N')){
System.out.println("Please enter the height in inches: ");
heightInInches = input.nextFloat();
System.out.println("Please enter the weight in pounds: ");
weightInpounds = input.nextFloat();
heightInInches = 0.0254f * heightInMeters2;
weightInpounds = 0.453592f * weightInKilograms2;
BMI = weightInKilograms / (heightInMeters * heightInMeters);
System.out.println("The resulting BMI of the person is: " +BMI);
if (BMI < 18.5){
System.out.println("The personis underweight");
}
else if ((BMI<=25.0) && (BMI >= 18.5)){
System.out.println("The person is normal");
}
else if ((BMI >= 25.0) && (BMI <=30.0 )){
System.out.println("The personis obese");
}
else if(BMI>=30.0) {
System.out.println("The person is obese and should exercise");
}
}
else {
System.out.println("Please make sure you run the program again and then only use the characters n,N,y,Y. ");
}
}
}
This is the error message: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - variable BMI might not have been initialized
at uly14th.BmiCalculator.main(BmiCalculator.java:82)
At the row (line 82)
BMI = weightInKilograms / (heightInMeters * heightInMeters);
you use the variables weightInKilograms and heightInMeters which has never been initialized, hence your error.
I suspect you want to do the conversion to meters and kilograms from inches and pounds before calculating the BMI. You can do this by simply putting the following lines before the BMI calculation
heightInMeters = 0.0254f * heightInInches;
weightInKilograms = 0.453592f * weightInPounds;
BMI = weightInKilograms / (heightInMeters * heightInMeters); //Now you can calculate the BMI using your variables since they have been assigned a value and is therefore initialized
heightInMeters = 0.0254f * heightInInches ;
weightInKilograms = 0.453592f * weightInpounds ;
BMI = weightInKilograms / (heightInMeters * heightInMeters);
should do the trick (... in case the constants are correct)

Calorie Counter Calculator for Computer Science 1

System.out.print("Your BMR is:");//BMR Calculation
if (gender == ('M')){
System.out.println(665+(6.23 * weight)+(12.7 * height)-(6.8 * age));
} else if (gender == ('F')) {
System.out.println(655+(4.35 * weight)+(4.7 * height)-(4.7 * age));
};
I can get the result from the if-loop above to produce the BMR. However, I can't seem to get the BMR result to be input into the bottom if-loop to produce the exercise calculation.
System.out.println("What is your exercise routine, on the scale of 0 to 4? 0 is lowest and 4 is highest ");//Exercise Calculation
int exercise = sc.nextInt();
if (exercise == 0) {
System.out.println(BMR * 1.2);
} else if (exercise == 1) {
System.out.println(BMR * 1.375);
} else if (exercise == 2) {
System.out.println(BMR * 1.55);
} else if (exercise == 3) {
System.out.println(BMR * 1.725);
}else if (exercise == 4) {
System.out.println(BMR * 1.9);
};
You should be storing the value of BMR into a local variable so that you can access it later on in your code.
Here's an example:
System.out.print("Your BMR is:");//BMR Calculation
double BMR = 0;
if (gender == ('M')){
BMR = 665+(6.23 * weight)+(12.7 * height)-(6.8 * age);
System.out.println(BMR);
} else if (gender == ('F')) {
BMR = 655+(4.35 * weight)+(4.7 * height)-(4.7 * age);
System.out.println(BMR);
};
And then you can use that BMR double variable later on.

How to print variable

In my code I need to print out the tax variable. It's not working and I think I know why I just don't know how to do it. I need to initialize the variable tax but I don't know how to in a main class. Here is my code.
System.out.println("Enter your income!");
double income = scan.nextDouble();
if (income < 50000)
{
double tax = income / 100;
}
else if (income < 75000)
{
double tax = income / 100 * 2;
}
else if (income < 100000)
{
double tax = income / 100 * 3;
}
else if (income < 250000)
{
double tax = income / 100 * 4;
}
else if (income < 500000)
{
double tax = income / 100 * 5;
}
else if (income > 500000)
{
double tax = income / 100 * 6;
}
double tax = 0.0;
This line should be above the rest of your code. Then in your if statements remove the declarations of tax and instead just assign your expressions to tax:
tax = income / 100 * some number;
What is happening in your code right now is that there is a different tax variable for each else if statement you have, and because of the behavior of scope in java the program can only see the tax variable inside the else if that it is declared in. For example:
if(condition){
double tax = number;
}
else if(condition){
double tax = number;
}
else{
double tax = number;
}
This code block is similar to what you have. The tax variables in this code block can only be used inside their respective code blocks. Only between the curly braces does each tax variable exist. Once you leave the curly braces that variable no longer exists. It is deleted by java. Then when you reach the next set of curly braces and declare tax anew it is an entirely different variable as compared to this code
function(){
double tax = 0.0;
if(condition){
tax = number;
}
else if(condition){
tax = number;
}
else{
tax = number;
}
}
tax is the same variable throughout the if statements here because it exists between the curly braces of the function and not only between the curly braces of an if statement because it was declared outside the if statements.

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);

Working out taxable income Java

I have just finished a Java test at university and I know that I have answered a particular question wrong and would just like some help / clarification please?
The question was as follows:
implement a method that takes someones income and works out the tax.
If that person earns less than 7500 then tax = 0.
If that person earns between 7501 and 45000 then tax = 20%, less the 7500, which is tax free.
Finally, if that person earns above 45001 then tax = 40%, less the income in the 20% bracket, and then less the 7500 which is tax free.
As time was running short, I just did a basic if else statement showing income and tax brackets, example below.
public static double incomeTax(double income){
if(income <= 7500){
income = income * 0;
}
else if(income >= 7501 && income <= 45000){
income = income * 0.8;
}
else(income >= 45001){
income = income * 0.6;
}
return income;
}
I know that the code is not correct, no where near, but as it was coming to the end of the test I gave it a go in a hope just to get a mark for the if else statements.
I would really appreciate any help here.
Thank you.
After great feedback, this is what I came back with (with a LOT of help!!:] )...
import java.util.Scanner;
public class TaxableIncome
{
public static void main(String[] args){
netIncome();
}
public static double netIncome() {
double income = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter income: ");
income = in.nextDouble();
System.out.println();
double tax1 = 0;
double tax2 = 0;
double totalTax = tax1 + tax2;
// high income bracket
if (income > 45000) {
double part1 = income - 45000; // part = income - 45000
tax1 += part1 * 0.4; // tax = tax + part * 0.4
System.out.println("High Tax Band - Greater than 45000: " + tax1);
}
// medium income bracket
if (income > 7500) {
double part2 = income - 7500;
tax2 += part2 * 0.2;
System.out.println("Medium Tax Band - Greater than 7500: " + tax2);
}
System.out.println("Total Tax = " + (tax1 + tax2));
// tax for low income is zero, we don't need to compute anything.
return totalTax;
}
}
A simple answer would be as this:
public static double netIncome(double income) {
double tax = 0;
// high income bracket
if (income > 45000) {
double part = income - 45000;
tax += part * 0.4;
income = 45000;
}
// medium income bracket
if (income > 7500) {
double part = income - 7500;
tax += part * 0.2;
}
// tax for low income is zero, we don't need to compute anything.
return tax;
}
This way you calculate the tax for each tax bracket and sum them.
I see nothing wrong with the logic. The main issue you had was you just need to return the income tax, not the total income. So the value you needed to return was income*whateverPercentTax.
Also, I would've tried:
if(income < 7001){
}else if(income >=45001){
}else{}
But that is just me.
I would start with something like this:
public static double incomeTax(int income) {
final double band00Income = (double) Math.min(income, 7500);
final double band20Income = (double) Math.min(income - band00Income, 45000 - 7500);
final double band40Income = (double) Math.max(income - 45000, 0);
final double tax = band20Income * 0.2 + band40Income * 0.4;
return tax;
}
Note that income is an int due to a peculiarity of the tax calculation in the UK - it also solves the problem with the unspecified cases between 7500.01 and 7500.99 inclusive.
A better solution would extract constants for all the magic numbers. An even better solution would generalise the bands and rates into a table so that they can be changed easily.
A complete answer might include test cases like this:
import org.junit.Assert;
import org.junit.Test;
public class TestTax
{
public static final double DELTA = 0.1;
#Test
public void testTax() {
Assert.assertEquals(0.0, incomeTax(-3000), DELTA);
Assert.assertEquals(0.0, incomeTax(0), DELTA);
Assert.assertEquals(0.2, incomeTax(7501), DELTA);
Assert.assertEquals(3000.0, incomeTax(22500), DELTA);
Assert.assertEquals(7500.0, incomeTax(45000), DELTA);
Assert.assertEquals(7500.4, incomeTax(45001), DELTA);
Assert.assertEquals(25500.0, incomeTax(90000), DELTA);
}
public static double incomeTax(int income) {
final double band00Income = (double) Math.min(income, 7500);
final double band20Income = (double) Math.min(income - band00Income, 45000 - 7500);
final double band40Income = (double) Math.max(income - 45000, 0);
final double tax = band20Income * 0.2 + band40Income * 0.4;
return tax;
}
}
You'd have to tax things in bands. Dirty (untested) code:
public static double incomeTax(double income){
double tax = 0;
if(income > 7500){
tax += Math.min(45000-7500, income-7500)*.2;
}
if(income > 45000){
tax += (income-45000)*.4;
}
return tax;
}
You need to attempt to apply the tax rates more than once. Your code only hits one tax bracket. If I made 100k, I would have been taxed at 40% for the whole 100k. Here is something I came up with quickly.
public static double incomeTax(double income)
{
double tax = 0.0;
int midLevel = 7500;
int highLevel = 45000;
if (income <= 7500)
{
// Could early exit at this point and return already set tax
tax = 0.0;
}
if (income > midLevel)
{
// Find range of income > 7500, less than 4500. 37499 max
double taxableIncome = Math.min(income - midLevel, highLevel - midLevel - 1);
tax += taxableIncome * 0.2;
}
if (income > highLevel)
{
// Income above 45k
double taxableIncome = income - highLevel;
tax += taxableIncome * 0.4;
}
return tax;
}
You could try this, just copy your income brackets in the bracket array. Make sure you have infinity in bracket array and start with 0 in rate array.
import java.util.Scanner;
import java.text.DecimalFormat;
class IncomeTaxWithBrackets {
public static void main(String[] args) {
double infinity = Double.POSITIVE_INFINITY;
double [] bracket = {0, 7565, 25903, 54987, 121121, 567894, infinity};
double [] rate = {0, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35};
// bracket[0] to bracket[1] are assigned rate[1]
double income = 0;
double tax = 0;
System.out.print("\nPlease enter your income: ");
Scanner keyboard = new Scanner (System.in);
DecimalFormat dollar = new DecimalFormat ("$#,##0.00");
income = keyboard.nextDouble();
int x,i;
for (i=0; i <= 5; i++) {
if (income > bracket[i] && income <= bracket[i+1]) {
for (x=0; x<i; ++x) {
tax = tax + (bracket[x+1] - bracket[x]) * rate[x+1];
}
tax = tax + (income - bracket[i]) * rate[i+1];
}
}
System.out.println("\nWith a taxable income of "+dollar.format(income)+", your personal income tax is "+dollar.format(tax));
}
}
Let me know what you think.

Categories

Resources