程序在读取文件时,要求用户输入的密码是tiger123。如果输入了正确的密码,程序将读取名字是word.txt的文件。程序允许用户两次输入的密码不正确,一旦超过两次,程序将立刻退出。用Java语言完善并在IDEA环境下运行下列程序PassWord.java import java.io.*; public class PassWord { 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("tiger123")) { 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) { //从文件中读取数据 } } }
时间: 2023-06-14 15:02:33 浏览: 82
以下是完善后的PassWord.java程序:
```java
import java.io.*;
public class PassWord {
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("tiger123")) {
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) {
try {
FileReader fr = new FileReader("word.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
该程序使用Console类的readPassword方法读取用户输入的密码,使用FileReader和BufferedReader读取文件内容。如果用户输入的密码不正确,程序会提示用户并且计数器会加1,如果用户连续三次输入的密码都不正确,程序将会退出。如果用户输入的密码正确,程序将会读取名字为word.txt的文件,并输出文件内容。