Home > other >  java if statements with math equation
java if statements with math equation

Time:09-16

I'm trying to make a code that applies tax rates to an input but I keep getting an error that says that i'm duplicating a local variable...

    System.out.print("What percentage do you want to withhold for your medical savings account? ");

    mw = pd.nextDouble();
    taxtotal = gross - ud - mw;
    Double taxtotal = pd.nextLine();
    Double taxtotal = pd.next();
    if (taxtotal > 2500) {
        taxtotal * 0.25;
    }
        

CodePudding user response:

taxtotal variable declared 2 times. Variable can be declared one time and can be used as many times you want.

Variable declaration is, datatype and variable name ex:

Datatype variableName;

In the declaration itself we can do assignment also, like setting some value after equal sign.

Datatype variableName = value;

CodePudding user response:

  1. Adding Data type before the variable name is called Declaring a Variable. Eg - int sum, Double taxtotal, char ch etc.

  2. You cannot use nextLine() method to store value in data types other than String. i.e.-

    double taxtotal = pd.nextLine(); //This is wrong
    

    The nextLine() method belongs to String data type. i.e.- You can use it only for String Variables otherwise it gives "incompatible types: String cannot be converted to double" compiletime error. e.g.-

    String name = pd.nextLine();
    
  3. You can declare variables only once. i.e. No need to Declare Data Type for Variable Each/Every time you use. i.e. Redeclaring the same variable you declared before gives you compiletime error! e.g -

    double taxtotal;            //Declaring Variable
    taxtotal = 0.00d;           //Initializing the variable
    taxtotal = pd.nextDouble();   //Reading and storing value in the variable
    
  4. To dump the \n after nextLine() method used, you dont need to store it. i.e. just call the next() method without storing into variable.

    taxtotal = pd.nextLine(); //nextLine() method called
    pd.next();          //calling next() function without storing in variable to dump \n
    
  5. To save the mathematical operation you performed, you need to copy the output value to the respective variable otherwise the new value wont be saved.

    if (taxtotal > 2500) {
        taxtotal = taxtotal * 0.25; //updating and storing the multiplication value in taxtotal
    }
    
  • Related