运行此代码时为什么会出现NullPointerException?

时间:2014-07-25 09:22:59

标签: java input nullpointerexception char

为什么我在运行这段代码时遇到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)

3 个答案:

答案 0 :(得分:0)

看起来sc.findInLine(".")在这里返回null。根据{{​​3}},

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. 

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

答案 1 :(得分:0)

所以整个班级都没有包含在您的代码段中,我觉得以下可能是有问题的区域

  1. 您可能忘记在 System.out.println(x)中设置x;
  2. 可能没有“。”在您 sc 对象中,因此sc.next(".")返回null
  3. 尝试使用null对象时,Java应用程序中会抛出NullPointerException。当您尝试调用null对象的实例方法时,会发生此错误。例如,您有一个对象sc.next(".")返回一个空对象,并且您正在尝试使用此对象访问charAt(0)方法。

    如果你还有一些困惑,请发布你的全班

答案 2 :(得分:0)

尝试以下方法:

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