[英]Variable not initialized error?
好的,所以我运行这段代码,它给了我错误:
SammysRentalPriceWithMethods.java:49: error: variable Minutes might not have been initialized
int TOTAL_COST = Minutes - 60 * 1 + 40;
^
我不知道如何解决它,也很抱歉,如果我的代码效率低下,我刚接触Java 3个星期,这对初学者来说非常重要。
import java.util.Scanner;
public class SammysRentalPriceWithMethods {
public static void main(String[] args) {
rentalTime();
companyMotto();
whenIGetMoney();
}
public static int rentalTime() {
int Minutes;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Enter total minutes equipment was rented:");
Minutes = inputDevice.nextInt();
return Minutes;
}
public static void companyMotto() {
System.out.println(
"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS \r\n" +
"S S \r\n" +
"S S \r\n" +
"S S \r\n" +
"S S \r\n" +
"S S \r\n" +
"S Sammy's makes it fun in the sun S \r\n" +
"S S \r\n" +
"S S \r\n" +
"S S \r\n" +
"S S \r\n" +
"S S \r\n" +
"S S \r\n" +
"SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS \r\n");
}
public static void whenIGetMoney() {
final int HOURLY_RATE = 40;
final int EXTRA_MIN_RATE = 1;
int Minutes;
int TOTAL_COST = Minutes - 60 * 1 + 40;
System.out.println("You rented our equipment for " + Minutes + " minutes!");
System.out.println("The total cost of an " + Minutes + " minute rental is $" + TOTAL_COST + ".");
}
}
我在最后一个方法中遇到错误,告诉我未初始化变量Minutes,有什么想法吗?
您必须先初始化局部变量才能使用它。 您的Minutes
变量未初始化,您尝试使用它。 就像int Minutes = 0;
一样声明它int Minutes = 0;
在whenIGetMoney()
方法中。 无论如何,结果不会像您期望的那样,因为变量Minutes
中的值不正确。
我认为您应该尝试这样做:
int min = rentalTime();
companyMotto();
whenIGetMoney(min);
进行以下修改:
public static void whenIGetMoney(int min) {
final int HOURLY_RATE = 40;
final int EXTRA_MIN_RATE = 1;
int Minutes = min;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.