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);
}
}
It does not get initialized if the last else if statment occures and x < 50 or when none of the if statements result in true for mailWeight. You could preinitialize cost. (double cost = 0) Or you could add all missing else blocks. You need to initialize your variable in all possible cases before reading it.
This would probably work:
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;
} else {
cost = 0; // Or whatever you want to set it to in this case
}
} else {
cost = 0; // Or whatever you want to set it to in this case
}
System.out.println(cost);
}
Or preinitializing the cost value:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double mailWeight;
double cost = 0; // Or whatever you want it to be if none of the cases match
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);
}