Search code examples
javainitialization

Is this the right way to initialize a variable


Is it bad practice to set newWeight to 0.0 (before the switch block) before I use it? If i just declare it, I get an error in the complier saying variable newWeight might not have been initialized.

import java.util.*;

public class SpaceBoxing {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        System.out.print("Please enter your current weight ");
        float weight = s.nextFloat();

        System.out.println("I have information on the following planets");
        System.out.println("1. Venus  2. Mars   3. Jupiter");
        System.out.println("4. Saturn 5. Uranus 6. Neptune");
        System.out.println(" ");
        System.out.println("Which planet are you visiting");

        int planet = s.nextInt();
        double newWeight = 0.0;

        switch(planet){
            case 1:
                newWeight = weight*0.78;
                break;
            case 2:
                newWeight = weight*0.39;
                break;
            case 3:
                newWeight = weight*2.56;
                break;
            case 4:
                newWeight = weight*1.17;
                break;
            case 5:
                newWeight = weight*1.05;
                break;
            case 6:
                newWeight = weight*1.23;
                break;
        }
        System.out.println("Your weight would be " + newWeight + " pounds on that planet");
    }
}

Solution

  • You don't need to instantiate it before your switch but you should include a default case to the switch where you assign a value or perhaps throw an exception. The default case will be executed in the event that the previous cases do not cover the supplied argument.

    int planet = s.nextInt();
    double newWeight;
    
    switch(planet){
        case 1:
            newWeight = weight*0.78;
            break;
        case 2:
            newWeight = weight*0.39;
            break;
        case 3:
            newWeight = weight*2.56;
            break;
        case 4:
            newWeight = weight*1.17;
            break;
        case 5:
            newWeight = weight*1.05;
            break;
        case 6:
            newWeight = weight*1.23;
            break;
        default:
            newWeight = 0.0;
            // or
            throw new IllegalArgumentException();
    }