变量未初始化错误?

时间:2014-09-22 19:32:17

标签: java

好的,所以我运行此代码,它给了我错误:

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没有初始化,有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果不首先初始化本地变量,则无法使用它。您的Minutes变量未初始化,您尝试使用它。只需在int Minutes = 0;方法中将其声明为whenIGetMoney()即可。 无论如何,结果将不是您期望的结果,因为变量Minutes中没有正确的值。

答案 1 :(得分:1)

我想你应该试试这个:

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;
    ...