【问题标题】:Why I get the java.lang.NullPointerException? [duplicate]为什么我得到 java.lang.NullPointerException? [复制]
【发布时间】:2015-07-16 00:48:09
【问题描述】:

我想输入一个名字并打印第一个字符 ....

public class Test {

    public static void main(String[] args) {

        Console console = System.console();
        System.out.println("Type your name : ");
        String inputChar = console.readLine();

        char firstChar = inputChar.charAt(0);

        System.out.println(firstChar);



    }
}

【问题讨论】:

标签: java nullpointerexception


【解决方案1】:

某些 IDE 将为 Console 类返回 NPE。您可以使用 Scanner 类并轻松完成:

试试这个:

      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a Name:");
      String s = scan.next();
      System.out.println(s.charAt(0));

这将打印输入字符串的第一个字母。

【讨论】:

  • +1 作为替代方案。 Scanner 类有很多有用的功能,并且可以处理可能发生的异常。
【解决方案2】:

使用 Console 类有时可能有点不可靠。

对于读取控制台输入,最好使用 Scanner 类或 BufferedReader。 您可以使用像这样的扫描仪:

Scanner scanner = new Scanner(System.in); // System.in is the console's inputstream
System.out.print("Enter text : ");
String input = scanner.nextLine();
// ^^ This reads the entire line. Use this if you expect spaces in your input
// Otherwise, you can use scanner.next() if you only want to read the next token
System.out.println(input);

你也可以像这样使用 BufferedReader:

Java 7 之前的语法

try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter text : ");
        String input = br.readLine();
        System.out.println(input);
        br.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

Java 7 语法

try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

        System.out.print("Enter text : ");
        String input = br.readLine();
        System.out.println(input);

    } catch (Exception e) {
        e.printStackTrace();
    }

注意:调用 br.readLine() 时需要使用 try-catch 语句,因为它会抛出 IOException。

如果您想读取标记(由空格分隔的文本块),您可以使用 Scanner。如果您想简单地从 InputStream 中读取,请使用 BufferedReader。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多