Java byte stream read function

Issues into

Java get the job done from the standard input stream user input, uses System.in.read(), and then there was bug.

//随机生成一个小写字母,用户猜5次,读取用户输入,并判断是否猜对
import java.io.IOException;
public class LetterGuessing {
    public static void main(String[] args) throws IOException {
        char ch,answer;
        //随机生成字母
        answer=(char)(Math.random()*26+'a');
        System.out.print("请输入一个小写字母:");
        for(int i=1;i<=5;i++) {
            //获取用户输入,可能抛出异常
            ch=(char)System.in.read();
            //比较大小
            if(ch == answer){
                System.out.println("恭喜,正确!用了"+i+"次猜对");
                break;
            }
            else if(ch > answer)
                System.out.println("您猜大了,还有"+ (5-i) +"次机会");
            else
                System.out.println("您猜小了,还有"+ (5-i) +"次机会");
        }
    }
}

Enter the characters 'a', press Enter, and so I did not enter the next cycle will run three times.

Source of the problem

System.in.read()Byte read, read into a byte. Behind a detailed explanation.

After commissioning, it can be seen in three cycles ch, respectively a, \r, \n.

Why a + Enter, will become a \ r \ n it

Read and write files in two ways in the presence of Windows, a binary way, the other is text .

Text when you write "wrap" will become "carriage return - line feed" that \ r \ n; read "Enter - wrap" will become "wrap."

Binary read and write in strict accordance with a byte by byte manner.

Here, although not used files, but the truth should be the same

A read()function in accordance with the read byte by byte, i.e., binary.

May be derived, we input data in the input stream according to the default text.

Solution

method one

After the first 10 lines of code, plus two rows System.in.read();

Object is read out / r in the input stream and / n.

The limitations of this approach is that the input can not add a space before and after the letter, because it does not make a space removed from the input stream.

Method Two

Do not read()read replaced by the following code

import java.util.Scanner;
Scanner input=new Scanner(System.in);
ch=input.next().charAt(0);

This method is better, read the string (ignores spaces and line breaks, spaces and line breaks do not remain in the input stream), then take the first character of the string.

Knowledge Point

System.in

The official document: https: //docs.oracle.com/javase/10/docs/api/java/lang/System.html#in

SystemIs a class, in is Systema member of the official described as follows:

public static final InputStream in

The “standard” input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.

inIs a InputStreamtype of object, so only need to know InputStreamcan be.

InputStream

The official document: https://docs.oracle.com/javase/10/docs/api/java/io/InputStream.html

public abstract class InputStream   //抽象类
extends Object          //继承Object类
implements Closeable    //实现Closeable接口

The official described as follows:

This abstract class is the superclass of all classes representing an input stream of bytes.

Translated as: This abstract class is the superclass of all byte stream classes.

Meaning the byte stream: reading method is read byte by byte , and the two-byte character stream read two bytes.

Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input.

Translation of: a need to define InputStreamapplication subclass must provide a return to the next byte input method (function).

read()

The official document: https: //docs.oracle.com/javase/10/docs/api/java/io/InputStream.html#read ()

public abstract int read() 
                throws IOException

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to255.

This is the key, it returns the next byte ASCII code

If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

A subclass must provide an implementation of this method.

Returns:

the next byte of data, or -1 if the end of the stream is reached.

Throws:

IOException - if an I/O error occurs.

Author: @ smelly salted fish

This article original author, please indicate the source: https://chouxianyu.github.io/2018/09/22/Java byte stream read function / # more

Forwarding and comments welcome

Guess you like

Origin www.cnblogs.com/chouxianyu/p/11270035.html