Search code examples
javafor-loopsyntax-errorundefined-symbol

Error while compiling in for loop


When trying to compile my file AverageRainfall.java, I keep getting an error for my variables that two symbols do not exist. I have included the affected code, which includes the two defined variables and the System.out.print command that is receiving the error.

System.out.println("Enter the rainfall, in inches, for each month. ");          
for(int y = 1; y <= years; y++)

  for(int m = 1; m <= NUM_MONTHS; m++);     

System.out.print("Year" + y + "month" + m + ": ");        
monthRain = keyboard.nextDouble();

What am I doing wrong that I consistently get this error for both 'y' and 'm':

AverageRainfall.java:26: error: cannot find symbol

After adding the changes suggested by first commenter, I no longer receive the 'cannot find symbol' error, but now I am told that 'y' and 'm' may not have initialized, and it is giving me an error for the while loop directly following it. Affected code:

    {
   System.out.println("Enter the rainfall, in inches, for each month. ");
      for(int y = 1; y <= years; y++){
         for(int m = 1; m <= NUM_MONTHS; m++){

          System.out.print("Year" + y + "month" + m + ": ");
          monthRain = keyboard.nextDouble(); 
         }
      }
         while (monthRain < 0)
      {
         System.out.print("Invalid. Enter 0 or greater: ");
         monthRain = keyboard.nextDouble();
      }
}

AverageRainfall.java:32: error: variable monthRain might not have been initialized


Solution

  • Your m is wrongly initialized

    int m = m;
    

    This should fail as m does not have a value assigned yet. Did you mean int m = y; ?