0
public static void main(String[] args) throws Exception {
    System.out.println("Enter");

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    {
        int c;
        int count = 0;
        while ((c = input.read()) != -1) {

            System.out.println(+count);
            count++;

        }

    }
}

Using the read() method only I want to print the count of each char, Eg: if my input:the star then output should be: 9, but when I try to put the count outside the loop my program never comes out of loop and print the total count value, readline(), next(), hasnext() methods doesn't count char by char so they give me a wrong result

1 Answer 1

1

Your while loop never exits because the read method never returns -1. It only does that when the stream reaches end of file (EOF). The underlying stream that the BufferedReader uses (System.in) has to be closed in order for that to happen.

I'm not sure what your requirements are but if you're looking to read one line of input from the console and determine how many characters that line has, you could do something like this:

Scanner sc = new Scanner(System.in);
String line = sc.readLine();
int charCount = line.length();
System.out.println("Characters count: " + charCount);
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.