Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop variable cannot be resolved to variable after loop

Tags:

java

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'm a beginner at Java. When I run this code, I get the error message that counter cannot be resolved to a variable. How do I fix this? I tried converting counter to a string, but that did nothing.

like image 237
Mr. Stuffandthings Avatar asked Jan 10 '23 07:01

Mr. Stuffandthings


1 Answers

The variable counter only exists within the scope of the loop. In order to reference it after the loop, you'll need to define it outside of 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);
    }
}

Note that conversely, char a can be declared within the scope of the for loop, since it is not used outside of the loop.

like image 181
DreadPirateShawn Avatar answered Jan 26 '23 01:01

DreadPirateShawn