Search code examples
javavariablesinitializationlocal-variablesclass-variables

Trouble initializing local/class variables


public class ClassName {

   public static void main(String[] args) {
   //code: depending on user input runs Methodname1();
   }

      public static void MethodName1 {

        double kgs;
        double totalIn;

        //code: do/while try/catch etc.


        double ImpToMetBmi;
        double InchToMtrH;

        InchToMtrH = totalIn*2.54/100;

        ImpToMetBmi = (kgs/(InchToMtrH*InchToMtrH);

        System.out.printf("\nYour BMI is: %.3f\n" ,ImpToMetBmi);
      }
}

Really sorry for the long and badly written code. I think all code/layout must be seen to figure out the problem.

Errors I'm getting: Exception...Uncompilable source code - variable totalIn might not have been initialized Exception...Uncompilable source code - variable kgs might not have been initialized

This formula worked before I inserted do/while try/catch statements for exception handling. I have spent hours reading about declaring and initilizing variables, local and class variables. I've tried a few different ways but nothing I try fixes the problem. I'm confused as to what is causing this and how to fix it. I'd like to figure this out and understand the solution. Where do I initialize 'totalIn' and 'kgs'? and What to I initialize them as? These varialbles are populated by values inputted by the user through Scanner if that makes any difference. Please help!


Solution

  • Here is an example that explains the cause you are getting and why you are getting that -

    double test;
    if( isTrue){
        test = 2.0d;`enter code here`
    } 
    // This will give you a error stating that test might have not initialized
    double calculate = test * 5.0;
    

    Reason is clear if condition in if block is true then the test value will be initialized with 2.0 other wise it will be uninitialized.

    A quick fix to this might be initializing test to some value (may be 0).

    Coming to you point, to initialize those variables you can do following things -

    static double kgs;
    static double totalIn;
    public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      kgs= sc.nextDouble;
      totalIn = sc.nextDouble();
    }
    


    or pass them as method parameter like below -

    public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      double kgs = sc.nextDouble;
      double totalIn = sc.nextDouble();
    }
    
    public void yourMethod(double kgs, double totalIn){
      // do whatever you want with above passed variables
    
    }