首页 > 解决方案 > 如何允许 Java 从扫描仪中获取 /n 并打印 ASCII 值

问题描述

我在 codeZinger 上做一个 java 项目,我需要从扫描仪中获取一个字符值并打印 ASCII 值。到目前为止,我拥有的代码适用于除“/n”字符之外的所有内容。在这种情况下,codezinger 返回错误“线程“main”java.lang.NullPointerException 扫描程序中的异常”。

我在下面附上了我的代码,我已经尝试了所有方法,但它不起作用。我是 C++ 的 Java 新手。

我什至尝试使用 if 语句手动测试 /n 并且没有用

public class Solution {
    public static void main(String[] args) {
        
        //creating input stream
        Scanner input = new Scanner(System.in);
        

        // allows character input from input stream
        char charIn = input.findInLine(".").charAt(0);
            if(input.equals("\\n"))
        {
            System.out.print("10");
        }
        // casts character to type int to get ascii value
        
         int intVal = (int)charIn;  
    
    
        System.out.print(intVal);
    }
}

标签: javaascii

解决方案


int code;
while ((code = System.in.read()) != -1) {
    System.out.format("0x%02X ", code);
}

推荐阅读