Search code examples
javaandroidif-statementandroid-studioidentifier

If statement not compiling in Android Studio - identifier expected and unexpected token error


I'm working on an application for calculating income versus expenses. I'm trying to output a grade based on the income versus expenses from A to F.

Only one problem: my if loop won't compile. I have seen this happen once or twice in Android studio. Not sure of the cause. Maybe someone can help shed some light on it.

The if statement is giving me an identifier expected and unexpected token error.

package ericleeconklin.costoflivingcalculator;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.*;
import java.io.Console;


public class FinalGrade extends ActionBarActivity {


Bundle b = getIntent().getExtras();
double rentMortgage = b.getDouble("rentmortgage");
double utilities = b.getDouble("utilities");
double insurance = b.getDouble("insurance");
double phoneInternet = b.getDouble("car");
double food = b.getDouble("phone");
double carPayment = b.getDouble("food");
double misc = b.getDouble("misc");
double myIncome = b.getDouble("myincome");

public double totalExpenses = rentMortgage+utilities+insurance+phoneInternet+food+carPayment+misc;
public double expensesToIncome = totalExpenses/myIncome;

//Calculate grade based on expenses to income ratio
String myGrade = "A";

if (expensesToIncome<0.25) {
    myGrade = "A";
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_final_grade);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_final_grade, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Solution

  • You have code outside a method. That is not allowed. You should place this code in a method body and then call this method. Example:

    Public String getGrade(double expensesToIncome){
      //Calculate grade based on expenses to income ratio
      String myGrade = "A";
    
      if (expensesToIncome<0.25) {
          myGrade = "A";
      }
      return myGrade;
    }