我正在处理这组代码,但遇到了“局部变量connat被初始化”的错误。我是在Java中编写代码的新手,我正在尝试学习基础知识。我知道变量需要初始化,但我不知道如何去做。我明白我可以做“int price = 0;”但总是会以$ 0的价格返回。任何帮助将不胜感激。本地变量无法初始化
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int price;
String customertype;
double bonus;
DecimalFormat df = new DecimalFormat("$#,###");
System.out.println("Are you a residential (r), commercial (c), Educational (e), or Preferred (p) customer?");
customertype = in .next().toLowerCase();
System.out.println("Please enter the number of minutes the customer used NkuTel services for the week");
double minutes = in .nextInt();
//Weekly rate of $5. 10 cents per minute over 60 mins.
if (minutes <= (0) && (minutes >= 10080)) {
System.out.println("Cannot have that amount of minutes. Please try again");
if (customertype.equals("r")) {
if (minutes > (60)) price = (int)((5 + .010) - 60);
if (minutes <= 60) price = 5;
} {}
//20 cents per minute for first 300. 15 cents per min after that
if (customertype.equals("c")) {
if (minutes <= 300) price = (int)(.20 * 300);
if (minutes >= 300) price = (int)(minutes * (.15));
if (minutes >= 300) bonus = (price * (-.30));
System.out.println("You get a bonus for being over 300 minutes!");
}
//Educational customer charged 18c per min.
if (customertype.equals("e")) {
price = (int)(.18 * minutes);
}
if (customertype.equals("p"))
if (minutes >= 500) price = (int)((minutes * .04) + 10);
if (minutes < 500) price = (int)((minutes * .06) + 10);
else
System.out.println("Error. Please enter either 'r' or 'c'");
}
/*Preferred customer pays $10 base and 6c per min.
if <500 then rate is 4c per min. */
// else{
// System.out.println("Error. Please enter either 'r' or 'c'");}
System.out.println("Your total minutes is " + minutes + ", your total bill is " + df.format(price));
}
}
如果'customertype'为'e',则'else'在else块中永远不会被初始化。您必须在所有分支中进行初始化。 – Li357
你在使用什么IDE,给出这样一个严重错误的错误? 'javac'表示*“变量价格可能没有被初始化”*,并且Eclipse说*“局部变量价格可能没有被初始化”*,两者都正确地识别问题,即问题是“有未被初始化“,不像你提到的”无法初始化“。 – Andreas