我想要使用Console类中的方法,readLine()和readPassword()方法,但是总是不能显示真确的结果,程序报错,说没有控制台,我也不知道具体是什么原因,请教高手,什么时候才有控制台啊,怎样改正这个程序啊,谢谢!package ConsolePassword; import java.io.Console; public class ConsolePassword { 
public static void main(String[] args) { 
Console cons=System.console(); 
String uname = cons.readLine("uname"); 
char[] password=cons.readPassword("password: "); 
System.out.println(uname); 
System.out.println(password); 
} } 

解决方案 »

  1.   

    直接在控制台运行吧,Eclipse不行的
      

  2.   

    这个程序只能在命令下运行。api是这样写的:
    此类包含多个方法,可访问与当前 Java 虚拟机关联的基于字符的控制台设备(如果有)。 虚拟机是否具有控制台取决于底层平台,还取决于调用虚拟机的方式。如果虚拟机从一个交互式命令行开始启动,且没有重定向标准输入和输出流,那么其控制台将存在,并且通常连接到键盘并从虚拟机启动的地方显示。如果虚拟机是自动启动的(例如,由后台作业调度程序启动),那么它通常没有控制台。 
      

  3.   

    JDK 6 中的 java.io.Console 的使用条件限制很多,具体的可以看看它的 API DOC。Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner
    in which the virtual machine is invoked. If the virtual machine is started from an interactive command line
    without redirecting the standard input and output streams then its console will exist and will typically be
    connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is
    started automatically, for example by a background job scheduler, then it will typically not have a console.文档上面明确地说明了,如果要有控制台不仅依赖于平台,而且取决于 JVM 的调用方式。而且虚拟机是从交互式的命令下
    启动的(不是后台程序启动的),并且没有重定向标准的输入和输出流,这时才会有控制台。Eclipse 中重新定向了标准输入和输出流,所以就获得不到 java.io.Console 的实例了。如果是在控制台运行这个程序的话,就可以使用 java.io.Console 了。
      

  4.   

    这个我以前错过,我知道怎么改,在Eclipse下得运行界面,不叫控制台,你切换到DOS界面下,用JAVA指令去执行,就可以了,那个就是控制台
      

  5.   

    这个我以前错过,我知道怎么改,在Eclipse下得运行界面,不叫控制台,你切换到DOS界面下,用JAVA指令去执行,就可以了,那个就是控制台