I just started learning about loops, but I keep running into the same problem whenever I try to execute a program. Likewise, even my professor's program examples are getting the same error. Here's the program, it's just a program I was practicing with
import java.util.Scanner;
public class BaseballStats {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SENTINEL = 0;
int hrs = 0;
int count = 0;
do
{
System.out.print("Enter the number of home runs from each team: ");
int homeruns = in.nextInt();
if(homeruns > 0)
{
hrs = hrs + homeruns;
count++;
}
}
while(homeruns != SENTINEL);
System.out.print("The average amount of home runs per team is: ");
System.out.println(hrs / count);
}
}
The problem I keep getting with this program and every other loop program I try, is that the variable inside the brackets (homeruns) is not defined when outside of the brackets.
while(homeruns != SENTINEL); simply states the the symbol variable homeruns doesn't exist, and if I initialize it at the beginning of the program, it simply won't work inside the brackets because it'll say the variable already exists.
I don't know if I sound like an idiot but I'm just so incredibly confused
homerunsinside your loop, so it cannot be referenced outside of it, which includes the control statement. Just declare it right before your loop.