public class calGrades
{
public static void main(String[] args)
{
int choice = 0;
while(choice != 4)
{
int size;
Scanner sizeScanner = new Scanner(System.in);
/* In the grades array, I get an error telling me that the local variable has not
yet been initialized. I want to initialize it using the scanner inside the if
statement*/
int[] grades = new int[size];
System.out.println("-----MENU-----");
System.out.println("1) Enter size");
System.out.println("2) Enter grades");
System.out.println("3) Calculate average");
System.out.println("4) Exit program.");
Scanner choiceScanner = new Scanner(System.in);
choice = choiceScanner.nextInt();
if(choice == 1)
{
System.out.println("Enter size");
sizeScanner = new Scanner(System.in);
size = sizeScanner.nextInt();
}
if(choice == 2)
{
/*If i initialize size = 0, and then try the print statement
below, it will print out a 0 instead of whatever is read
into it via the scanner. */
System.out.println(size)
System.out.println("Enter grades: ");
Scanner gradeScanner = new Scanner(System.in);
for(int i = 0; i < size; i++) //I get the same error here in my for loop.
{
grades[i] = gradeScanner.nextInt();
}
}
}
}
}
I am trying to initialize variable 'size' inside of the first 'if' statement. If i initialize the variable in there, it does not change the actual value of size. I undertand that it is outside of the scope, but I do not know how to get it to store in there. This also creates problems with my grades array since I need to know the size of 'size' to set the size of the array. The error I get is: The local variable size may not have been initialized Java(536870963)