You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用System.console获取用户输入触发NullPointerException求助

System.console() 返回Null引发NullPointerException的解决办法

你的代码中System.console()返回了null,调用readLine()时触发了空指针异常。这是因为System.console()仅在原生交互式终端/命令行环境中才能返回有效实例,在IDE运行窗口、非交互式执行场景下,JVM无法获取到对应的控制台对象,所以返回null。

解决方案1:使用Scanner(通用适配所有环境)

Scanner是Java中更通用的输入处理类,不受运行环境限制,代码修改如下:

import java.util.Scanner;

public class Systemlearn {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the Name:");
        String str = scanner.nextLine();
        System.out.println(str);
        scanner.close();
    }
}

解决方案2:在原生终端运行原代码

如果你坚持使用System.console(),需要在系统原生终端中执行程序:

  1. 编译代码:javac Systemlearn.java
  2. 在终端直接运行:java Systemlearn
    此时System.console()会返回有效实例,不会触发空指针。

解决方案3:使用BufferedReader读取输入

也可以通过BufferedReader结合System.in实现输入读取,同样适配所有环境:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Systemlearn {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the Name:");
        String str = reader.readLine();
        System.out.println(str);
        reader.close();
    }
}

内容的提问来源于stack exchange,提问作者Santhosh Kumar A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 04:45:38