简体   繁体   中英

A simple java program output is not as expected with IO

i've a code which is not working as expected, it has to do something with System.in.read() method. the program is meant to read from the console until i press 'c' or 'C'

import java.io.*;

public class Input{
    public static void main(String args[])throws IOException{
        char b;

        outer:
        do{
            b= (char)System.in.read();
            System.out.println(b);
            if(b=='c'||b=='C'){
               break outer;
            }
        } while(true);      
    }
}

output is

D:\ex\1>java Input
d
d



c
c

D:\ex\1>

why are there empty lines in the output

When you call read the first time, it reads 'd' and prints it with a new line (because you used println instead of print ). This explains the first new line. After the loop's first iteration, read is called again. This time, it reads the carriage return character '\\r' . The third time read is called, it reads the new line character '\\n' . That's why there are 3 new lines.

Where do those new line characters come from?

Each time you enter a character, you press "enter" right? That's the new line! Since you're using Windows, it inserts \\r\\n . While on my Mac, a new line is just \\n . That's why your code produces 2 instead of 3 new lines when run on my Mac.

The solution to this is not to read the new lines:

do{
     b= (char)System.in.read();
     if (b == '\r' || b == '\n') continue;
     System.out.println(b);
        if(b=='c'||b=='C'){break outer;}

}while(true);

Or you can use a Scanner :

char b;
Scanner sc = new Scanner(System.in);
outer:
do{
    b= sc.findWithinHorizon(".", 0).charAt(0);
    System.out.println(b);
    if(b=='c'||b=='C'){break outer;}

}while(true);

simply replace System.out.println(b); with

int a = (int) b;
if (a != 13 && a != 10) {
    System.out.println(b);
}

it will not print the char, if the int value of it is line feed and carriage return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM