局部变量可能尚未初始化(方法)

The local variable may not have been initialized(methods)

问题:程序显示 "The local variable userMonth may not have been initialize"。我看不到问题,我已尝试修复它。有人可以告诉我我哪里错了吗?

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

}

您有一个路径,在 returned 时无法初始化 userMonth。 (不管你我能看到什么,编译器将检查限制在方法的范围内。)

所以我认为您要完成的是“向用户询问所有 12 个月的降雨量并将每个月的响应保存在 'number' 和 return 中。

所以你的 'userAnswere' 应该是这样的:

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

另请注意,您有一个会产生不良结果的转换 - double 到 int - 所以尽管它是 double 的总数也将是一个整数。