Java 变量未初始化错误?
好的,我运行这段代码,它给出了一个错误:Java 变量未初始化错误?,java,Java,好的,我运行这段代码,它给出了一个错误: SammysRentalPriceWithMethods.java:49: error: variable Minutes might not have been initialized int TOTAL_COST = Minutes - 60 * 1 + 40; ^ 我不知道如何修复它,如果我的代码效率低下,我也很抱歉,我只在Java上呆了3个星期,我是个新手 import java.util.
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
变量未初始化,您尝试使用它。只需像int Minutes=0那样声明它在whenIGetMoney()
方法中的code>。
无论如何,结果不会是您期望的结果,因为变量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;
...
我想让你知道,我爱你。你。这工作做得很好!亲爱的宝贝耶稣,谢谢你!