Java的輸入和輸出遇到的一點問題

來源:互聯網
上載者:User

標籤: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的輸入和輸出遇到的一點問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.