我有一个简单的问题。
我有一个文本文件,其中包含以下记录:
HAMADA 115599
KARIM 224466
BOSY 47896512
此文件实际上定义了用户帐户的用户名和密码
现在我写了一个简单的代码来编辑特定用户的密码。
这是我的代码:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;
import java.util.Scanner;
public class Test6 {
public static void main(String[] args)throws IOException {
String newPassword=null;
boolean checked = true;
File f= new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt");// path to your file
File tempFile = new File("C:\\Users\\فاطمة\\Downloads\\accounts2.txt"); // create a temp file in same path
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
Scanner sc = new Scanner(f);
System.out.println("Change account password !!");
System.out.println("Validate your account please !!");
System.out.printf("Username: ");
Scanner sc2 = new Scanner(System.in);
String username = sc2.next().toUpperCase();
System.out.printf("Old Password: ");
String password = sc2.next();
while(sc.hasNextLine())
{
String currentLine= sc.nextLine();
String[] tokens = currentLine.split(" ");
if(Objects.equals(tokens[0], username) && Objects.equals(tokens[1], password) && checked)
{
sc2.nextLine();
System.out.printf("New Password: ");
newPassword= sc2.nextLine();
if(newPassword.length() >= 6)
{
currentLine = tokens[0]+" "+newPassword;
checked = false;
}
else
System.out.println("Short Password, Password must be at least 6 characters.");
}
else{System.out.println("Wrong username or password .. try again !!");}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
sc.close();
f.delete();
boolean successful = tempFile.renameTo(f);
if(successful == true)
System.out.println("Your password has been changed successfully.");
else
System.out.println("Error occurred during changing password, please try again.");
}
}
问题是:如果我在文件中有如上所述的许多记录,现在它将为每个记录停止写入“错误的用户名或密码”消息。我只是想让程序只在输入的记录中说这个消息,然后在程序中停止。如果在文件中找到记录,则允许用户更改该记录的密码
答案 0 :(得分:1)
您写入“错误的用户名或密码”的电话是在while
循环内,因此会为文件中与当前搜索参数不匹配的每一行调用它。要解决此问题,请将错误消息移到while
循环之外,以便只能调用一次。
这些错误很容易在正确缩进的代码中发现,因为它变得很明显循环内部和不循环内容。通常,使用适当的格式化可以使调试更容易。
编辑例如,你可以这样做:
// Open the file...
boolean found = false;
while(sc.hasNextLine())
{
// Read the line...
if (Objects.equals(tokens[0], username) && Objects.equals(tokens[1], password) && checked)
{
// Do stuff...
found = true;
break; // Done looking
}
}
if (!found)
{
System.out.println("Wrong username or password .. try again !!");
}
// Close the file...