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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With