Java的输入和输出遇到的一点问题

 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:
执行以上代码时,抛出了空指针异常
请输入你的年龄
20
20
请输入密码Exception in thread "main" 
java.lang.NullPointerException
at com.yunying.test.LearnIO.main(LearnIO.java:16)

原因是因为Console只支持在控制台中调用,不支持在ide中调用,其中的原理是 :只有从终端ternimal中启动jvm,才会有可用的console。

此时去终端中执行Java LearnIO时报错。

错误: 找不到或无法加载主类 LearnIO

注释首行包名问题解决

原文地址:https://www.cnblogs.com/raychou1995/p/9532941.html