1

I would like to send input to my program through standard in(the console) but when I do so, it sends two more characters, Carriage Return and Line Feed. I do not want my program to be reading these. Is there a way I can send what I typed without sending those characters?

Here is my code:

import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        while (true) {
            try {
                System.out.println(System.in.read());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Console output:

a <- Here I typed 'a' and hit enter
97 <- These three came from stdout
13 <-
10 <-
1
  • did you press enter after pressing a? if you're processing the input like this from the input stream, then just stop when you hit your custom termination character, if you're converting them to the string "a", trim off the carriage return/new lines. Commented Sep 12, 2014 at 16:44

2 Answers 2

2

You can use one of the classes which is designed to read in a line at a time, such as BufferedReader. This will pull in the line of text, but parse out the line termination characters:

while (true) {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println(reader.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Keep in mind that since this is pulling in the whole line, the output will be a String, rather than byte-by-byte.

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

Comments

1

Yes you can. One way would be to replace this,

System.out.println(System.in.read());

with

char ch = (char) System.in.read();
if (ch != '\r' && ch != '\n') {
  System.out.println((int) ch);
}

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.