【发布时间】:2018-08-17 19:08:48
【问题描述】:
现在已经四天了,我是初学者,我似乎无法完成这项工作。 因此,到目前为止,我的程序会询问用户名并在我打开的文件中查找匹配项。如果找到匹配项,它会询问用户密码,如果在文件中找到用户密码,它会检查用户名、密码,如果行中有特定的单词和凭据,它会打开一个凭据文件。 因此,如果用户名第一次输入正确,我的代码就可以工作,它会要求输入密码,然后中断或让用户查看文件。效果很好。
但如果用户名在第一次尝试时不正确,它永远不会检查第二次是否正确。它只是在 2 次尝试后结束(应该是 3 次失败的尝试)。 这是我的代码
public static void main(String[] args)throws Exception {
Scanner scnr = new Scanner(System.in);
//open credentials file
FileInputStream in = new FileInputStream ("./credentials.txt");
Scanner credentials = new Scanner(in);
// open zookeeper file
FileInputStream in1 = new FileInputStream ("./zookeeper.txt");
Scanner zookeeperInfo = new Scanner(in1);
FileInputStream in2 = new FileInputStream ("./admin.txt");
Scanner adminInfo = new Scanner(in2);
FileInputStream in3 = new FileInputStream ("./veterinarian.txt");
Scanner vetInfo = new Scanner(in3);
String userName = "";
String userPassword = "";
String original = "";
int numAttempts = 0;
boolean run = true;
while (run) {
System.out.println ("User Name or Q: ");
userName = scnr.nextLine();
if (userName.equals("Q") || numAttempts > 3) {
run = false;
System.out.println("Goodbye..");
}
else {
while(credentials.hasNextLine()) {
String line = credentials.nextLine();
if (line.contains(userName)) {
System.out.println(userName);
System.out.println("Gimme the password: ");
userPassword = scnr.nextLine();
original = userPassword;
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
if (line.contains(userName) && line.contains(sb.toString()) && line.contains("zookeeper")) {
while (zookeeperInfo.hasNextLine()) {
System.out.println(zookeeperInfo.nextLine() + " ");
}
break;
}
else if (line.contains(userName) && line.contains(sb.toString()) && line.contains("admin")) {
while (adminInfo.hasNextLine()) {
System.out.println(adminInfo.nextLine()+ " ");
}
break;
}
else if (line.contains(userName) && line.contains(sb.toString()) && line.contains("veterinarian")) {
while (vetInfo.hasNextLine()) {
System.out.println(vetInfo.nextLine() + " ");
}
break;
}
}
}
Picture of working part of the code Picture of non-working part
我真的不知道。我觉得我什至没有正确地做到这一点,但我所有的尝试都到此结束。我必须在星期天之前提交它,整个星期之后没有任何效果.. 请帮助,任何建议将不胜感激!
【问题讨论】:
-
你能把整个代码贴出来。无法确定 numAttempts 更改的位置。
-
请阅读minimal reproducible example并相应地完善您的问题。
-
你是否在任何地方增加
numAttempts? -
如何获得
credentials以及在哪里增加numAttempts -
a) 你的 while 循环方式太大了。试试看罗伯特马丁的“清洁代码”! b)您的格式(缩进!)很烂,没有IDE就不可能看到'c)是整个循环吗?好像缺少很多右括号。继续。
标签: java if-statement while-loop