1

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

1
  • 2
    You are declaring homeruns inside your loop, so it cannot be referenced outside of it, which includes the control statement. Just declare it right before your loop. Commented Feb 6, 2015 at 20:37

1 Answer 1

5

Declare it outside the loop and then don't redeclare it inside the loop:

int homeruns;
do
{
    System.out.print("Enter the number of home runs from each team: ");
    //int homeruns = in.nextInt();
    homeruns = in.nextInt();
    if(homeruns > 0)
    {

        hrs = hrs + homeruns;
        count++;

    }
}
while(homeruns != SENTINEL);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh my god, thank you so much. I've literally been stuck for like hours on this. Really appreciate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.