0

For some reason, when I try to run this code, it always return that it can't find the symbol b. Then I found that the problem was that the variable b can't be resolved to a variable. I have no idea why it is unable to resolve it to a variable.

class Q5 {
  public static void main(String[] args) {
    for (int iMus = 0; iMus < 10; iMus++)
    {
      int b = 19 + iMus;
    }
    System.out.println(b);
  }
}
Sankalpa Wijewickrama
  • 985
  • 3
  • 19
  • 30
Walker
  • 13
  • 1
  • 2
    because b only exists in the scope of the for loop. Maybe you meant to put the println in the loop? – OldProgrammer Feb 24 '22 at 03:15
  • 1
    When a local variable is declared, inside a pair of braces `{ }`, it ceases to exist once the `}` is reached. In this case, that's before your `System.out.println` call. – Dawood ibn Kareem Feb 24 '22 at 03:16

1 Answers1

1

It is because you declared the variable b within the loop. You try to print and access the variable outside the scope of the loop. That is not possible and please define the variable b outside the loop's scope. I will show an example below.

class Q5 {
  public static void main(String[] args) {
    int b = 0;
    for (int iMus = 0; iMus < 10; iMus++)
    {
      b = 19 + iMus;
    }
    System.out.println(b);
  }
}
Sankalpa Wijewickrama
  • 985
  • 3
  • 19
  • 30