variablesmethodsdrjava

The local variable may not have been initialized(methods)


Problem: The program says "The local variable userMonth may not have been initialize". I cannot see the problem, and I have tried to fix it. Can someone please tell me what I have wrong?

import java.util.Scanner;

public class Rainfall{
  public static void main(String[] args){
    Scanner keyboard= new Scanner(System.in);
    double total;

  int[] numbers= new int[12];

   total= userAnswere(numbers);

  }//
  public static double userAnswere(int[] number){
   Scanner keyboard= new Scanner(System.in);
  double userMonth;
  for(int i = 1; i < number.length; i++){
  System.out.println("Please enter a number for month "+i+" rainfall: ");
  userMonth= keyboard.nextDouble();
  userMonth+=number[i];
  }
  return userMonth;
  }

}

Solution

  • You have a path where userMonth could not be initialized when returned. (Despite what you and I can see, the compiler limits the check to the scope of the method.)

    So what I think you're trying to accomplish is this " Ask the user for rainfall for all 12 months and save each month response in 'number' and return a total.

    So your 'userAnswere' should be something like:

    public static double userAnswere(int[] number){
        Scanner keyboard= new Scanner(System.in);
        double userMonth = 0;
        for(int i = 0; i < number.length; i++){
            // assume user doesn't speak 0-based
            System.out.println("Please enter a number for month "+(i+1)+" rainfall: ");
            number[i] = keyboard.nextDouble();
            userMonth += number[i];
        }
        return userMonth;
    }
    

    Note also you have a cast which will yield undesirable results - double to int - so the total, despite it being a double will also be a whole number.