簡體   English   中英

為什么運行此代碼時會出現NullPointerException?

[英]Why am I getting NullPointerException when running this code?

為什么我在運行此代碼時收到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.findInLine(".")在此處返回null。 根據文檔

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. 您可能忘記了在System.out.println(x)中設置x
  2. 可能沒有任何“。” sc對象中,結果sc.next(".")返回null

當您嘗試使用null對象時,在Java應用程序中引發NullPointerException 當您嘗試調用一個為null的對象的實例方法時,發生錯誤。 例如,您有一個Object sc.next(".")返回一個空對象,並且您正在嘗試使用該對象訪問charAt(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);
} 
}

盡管將返回truefalse ,但這仍將檢查字符a是否在String中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM