Loop variable cannot be resolved after loop

import java.io.IOException;
import java.util.Scanner;

public class Chapter_3_Self_Test {
    public static void main (String args []) throws IOException {
        Scanner sc = new Scanner (System.in);
        char a;
        for (int counter = 0; a == '.'; counter++)  {
            a = (char) System.in.read();
        }
        System.out.println(counter);

    }
}

I am starting in Java. When I run this code, I get an error that the counter could not be resolved to a variable. How to fix it? I tried converting the counter to a string but did nothing.

+4
source share
1 answer

The variable counterexists only within the loop. To refer to it after the loop, you need to define it outside the loop:

import java.io.IOException;
import java.util.Scanner;

public class Chapter_3_Self_Test {
    public static void main (String args []) throws IOException {
        Scanner sc = new Scanner (System.in);
        int counter = 0;
        for (char a; a == '.'; counter++)   {
            a = (char) System.in.read();
        }
        System.out.println(counter);
    }
}

Please note that, on the contrary, it char acan be declared in the scope of the loop for, since it is not used outside the loop.

+9
source

Source: https://habr.com/ru/post/1546623/


All Articles