4
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.

1
  • 3
    the scope of your counter variable only exists in the for loop, define counter outside the for loop. Commented Jun 30, 2014 at 21:05

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

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.