vendredi 26 mars 2021

Initializing doubles in a loop giving error "variable might not have been initialized"

This program is supposed to get the weight of some mail from the user and calculate how much it costs. After 100g, the cost increases by $2.5/50g. However, when I try to run the program, it says "variable cost might not have been initialized". Is this because I am innitalizing it in an if statement or something? I know some people have had errors because they declare the variable in the if statment, but I have declared my variable outside the if statement. What am I doing wrong.

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        double mailWeight;
        double cost;

    System.out.println("How much does your mail weigh (g)");
        mailWeight = in.nextDouble();

        in.close();

        if (mailWeight > 0 && mailWeight <= 30) {
            cost = 4;
        }else if (mailWeight > 30 && mailWeight <= 50) {
            cost = 5.50;
        }else if (mailWeight > 50) {
            double x = mailWeight - 100;
            if (x >= 50) {
                double y = x/50;
                Math.ceil(y);
                double z = y * 2.5;
                cost = z + 7;
            }
        }
        System.out.println(cost);
  }
}

Aucun commentaire:

Enregistrer un commentaire