java - 为什么 `.read()` 一个数字的方法返回不同的数字

标签 java api

请解释一下System.in.read()的用途这个例子中的方法是我从另一个post那里学到的。作为初学者,我发现当我输入一个数字并在输出中得到不同的数字时不清楚,请澄清。

import java.io.IOException;

public class MainClass {

public static void main(String[] args) {
    int inChar;
    System.out.println("Enter a Character:");
    try {
        inChar = System.in.read();
        System.out.print("You entered ");
        System.out.println(inChar);
    }
    catch (IOException e){
        System.out.println("Error reading from user");
    }
}

最佳答案

System.in.read() 将值读取为其二进制值;例如,读取“a”将得到“97”的值 - 可以在此处获取此映射 https://www.asciitable.com/ .

为了在 Java 中获得此内容的文本表示,您需要将其读取为字符或字符串 - 字符是单个值,而字符串是字符一个接一个的组合。例如:

public class MainClass {

public static void main(String[] args) {
        System.out.println("Enter a Character:");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        System.out.print("You entered ");
        System.out.println(input);
}

查看 Scanner 类以了解其他选项,您可以使用scanner.nextInt() 来获取 Integer。

关于java - 为什么 `.read()` 一个数字的方法返回不同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50478934/

相关文章:

java - 对话框上的 NullPointerException - Android

java - Matlab与Java集成的方法

java - 适合 PHP 开发人员的最佳 Java Web 应用程序框架?

java - 如何实现回调?

Java:谷歌地图的替代品

javascript - PhoneGap.exec 不工作

jquery - jQuery连续有多个If语句

javascript - Uncaught ReferenceError : datapoint is not defined. 从 api 调用 json 数据时

python - Pymongo API 类型错误 : Unhashable dict

php - 使用 youtube api v3 验证视频是否存在