標籤:when null 指標 point style family str col api lips
1 //package com.yunying.test; 2 import java.io.Console; 3 import java.util.Scanner; 4 //學習io 5 public class LearnIO { 6 public static void main(String args[]) 7 { 8 @SuppressWarnings("resource") 9 Scanner in = new Scanner(System.in);10 System.out.println("請輸入你的年齡");11 String name = in.nextLine();12 System.out.println(name);13 System.out.println("請輸入密碼");14 Console cons= System.console();15 char[] passwd = cons.readPassword();16 System.out.println("輸入的密碼是"+passwd);17 in.close();18 }19 }問題1:這個時候eclipse會彈出一個警告:“Resource leak: ‘in‘ is never closed”查了下api,Scanner存在一個close方法,添加in.close;問題解決。其實eclipse給出瞭解決方案,@SuppressWarnings(“resource”),添加資源泄漏的警告,如果不關閉可能會存在資料浪費。“When a Scanner is closed, it will close its input source if the source implements the Closeable interface.”意思是當Scanner關閉時,system.in就會被關閉,system.in是一個常量流,所以使用close()涉及到資源的回收,一般是在main的最後去關閉scanner。 問題2:執行以上代碼時,拋出了null 指標異常
請輸入你的年齡2020請輸入密碼Exception in thread "main" java.lang.NullPointerExceptionat com.yunying.test.LearnIO.main(LearnIO.java:16)
原因是因為Console只支援在控制台中調用,不支援在ide中調用,其中的原理是 :只有從終端ternimal中啟動jvm,才會有可用的console。
此時去終端中執行Java LearnIO時報錯。
錯誤: 找不到或無法載入主類 LearnIO
注釋首行包名問題解決
Java的輸入和輸出遇到的一點問題