如果 希望在键盘输入一行文本,但是又不想让文本回显,即不在命令行中显示,那么就需要使用java.io包中的Console类的对象来完成
如下例题:
模拟用户输入的密码,如果输入正确(I love this game),那么,程序让用户看到“你好,欢迎你!”。程序允许用户两次输入的密码不正确,一旦超过两次,程序就会立刻退出
package test824;
import java.io.Console;
public class Test824 {
public static void main(String args[]) {
boolean success=false;
int count=0;
Console cons;
char[] passwd;
cons=System.console();
while(true){
System.out.print("输入密码:");
passwd=cons.readPassword();
count++;
String password=new String(passwd);
if(password.equals("I love this game")){
success=true;
System.out.println("第"+count+"次密码正确!");
break;
}
else{
System.out.println("第"+count+"次密码"+password+"不正确");
}
if(count==3){
System.out.println("您"+count+"次输入的密码都不正确");
System.exit(0);
}
}
if(success){
System.out.println("您好,欢迎你!");
}
}
}
这是书上的代码 然后我运行后是这样的。。。
感觉很神奇 ,也不知道咋错了,就返回了一个空值错误 然后请教请教学长,嗯就好了…
也就是说在cmd中运行才有效
然后 就复制粘贴在一个文本里,建立一个文件夹,修改文本的名字 .java 然后编译运行就好了…
(希望可以自己动手尝试尝试,我自己在弄得时候,就出现啥加载不到主类的问题,然后我把文本里的包名 删了就行了~)