【问题标题】:Why am I getting NullPointerException when running this code?为什么在运行此代码时出现 NullPointerException?
【发布时间】:2014-07-25 09:22:59
【问题描述】:

为什么我在运行此代码时收到 NullPointerException,我查了它是什么但仍然不明白如何修复它;请帮忙?

import java.util.Scanner;
public class Test{
public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        System.out.println();
        String User = sc.nextLine();
        char [] pass = System.console().readPassword();
        System.out.println(pass);
        char c = sc.next().charAt(0);
        System.out.println(c);
        char d = sc.findInLine("a").charAt(0);
        System.out.println(d);
        char b = sc.next().charAt(0);
        System.out.println(b);
        System.out.println(User);
} 
}

运行代码时一切正常,直到最后两行使用变量char b 输出的错误如下:

Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:11)

【问题讨论】:

  • 什么是“sc”,你如何确定它有两个“.”?
  • 因为sc.next(".") 返回null
  • 第 33 行是 char d = sc.findInLine(".").charAt(0);
  • 看起来 sc.findInLine(".") 返回 null
  • @Andy 我可以使用哪些参数从扫描仪中查找特定字符?我尝试用存在的字母替换".",它仍然给出NullPointerException

标签: java input nullpointerexception char


【解决方案1】:

尝试以下方法:

import java.util.Scanner;
public class Test{
public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        System.out.println();
        String User = sc.nextLine();
        char [] pass = System.console().readPassword();
        System.out.println(pass);
        char c = sc.next().charAt(0);
        System.out.println(c);
        String d = sc.next();
        boolean Contained;
        if(d.contains("a")){
           Contained = true;
        }
        else{ Contained = false; }
        System.out.println(d);
        System.out.println("Contains a ? " + Contained); 
        char b = sc.next().charAt(0);
        System.out.println(b);
        System.out.println(User);
} 
}

这仍然会检查该字符 a 是否在字符串中,尽管会返回 truefalse

【讨论】:

    【解决方案2】:

    看起来sc.findInLine(".") 在此处返回 null。根据documentation

    If no such pattern is detected in the input up to the next line separator, 
    then null is returned and the scanner's position is unchanged. 
    

    此外,当您将字符串模式传递给 findInLine 时,它​​最终的行为类似于 findInLine(Pattern.compile(pattern))

    【讨论】:

      【解决方案3】:

      虽然整个类没有包含在您的代码段中,但我觉得以下可能是有问题的区域

      1. 您可能忘记在 System.out.println(x) 中设置 x;
      2. 可能没有任何“。”在你的 sc 对象中,结果sc.next(".") 返回null

      当您尝试使用空对象时,Java 应用程序中会抛出 NullPointerException。当您尝试调用为空的对象的实例方法时会发生错误。例如,您有一个对象 sc.next(".") 返回一个空对象,而您正尝试使用此对象访问 charAt(0) 方法。

      如果你还有一些困惑,请发布你的整个课程

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 2013-02-05
        • 2020-12-15
        • 1970-01-01
        • 2013-01-03
        • 1970-01-01
        • 2011-09-30
        相关资源
        最近更新 更多