简体   繁体   English

System.out.println的未知输出

[英]Unknown output by System.out.println

I am learning Java and while studying try catch loop, I encountered this weird behaviour. 我正在学习Java,在学习try catch循环时,我遇到了这种奇怪的行为。

Whatever number I supply to the below code, it returns something between 49 - 53. 无论我向下面的代码提供什么数字,它返回49-53之间的东西。

public class demo{
    public static void main(String[] args) {
        System.out.println("Enter a number");
        try{
            int num = System.in.read();
            System.out.println(num);
        }catch(Exception e){
            e.printStackTrace();
        }       
    }
}

You must have entered numbers 1-5. 您必须输入数字1-5。 The read() method of InputStream ( System.in is an InputStream ) returns the byte value as an int , but the value is the Unicode code. InputStreamread()方法System.in是一个InputStream )将字节值作为int返回,但该值是Unicode代码。 The characters '1' through '5' are represented by the codes 49-53. 字符'1''5'由代码49-53表示。 In fact, '0' through '9' are represented by the codes 48-57. 实际上, '0''9'由代码48-57表示。

Don't call read directly on the InputStream . 不要直接在InputStream上调用read It's meant for low-level stream processing. 它适用于低级流处理。 Instead, wrap the InputStream in a Scanner and call nextInt() . 而是将InputStream包装在Scanner并调用nextInt()

InputStream.read() returns an integer. InputStream.read()返回一个整数。 You should do char c = (char) myInt; 你应该做char c =(char)myInt; to convert it to a character if that's what you want 如果这是你想要的,将它转换为一个角色

InputStream.read() reads only the next byte of data: InputStream.read()只读取下一个数据字节:

http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read() http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

If you'll need to read more than 1 byte of data at a time, try using a BufferedInputStream: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html or a reader: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html 如果您需要一次读取超过1个字节的数据,请尝试使用BufferedInputStream: http//docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html或读者: https//docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html

Beware of simply casting an int produced by InputStream.read to char - it will only work if your character set is ISO-8859-1. 谨防简单地将InputStream.read生成的int转换为char - 只有在您的字符集是ISO-8859-1时它才会起作用。 Hence, a Reader with appropriate Charset is a good option. 因此,具有适当Charset的Reader是一个不错的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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