我有一個簡單的問題。避免在使用java的文本文件中重複輸出?
我有有這樣記錄的文本文件:
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.");
}
}
的問題是:如果我有一個文件中多條記錄如上面提到的,現在它會爲每個記錄停止在寫消息「錯誤的用戶名或密碼」 。我只想讓程序只在輸入的記錄中說出這條消息,而不是在文件中找到,然後程序停止。如果在文件中找到了記錄,那麼它允許用戶更改該記錄的密碼
「程序崩潰」?你得到的確切例外是什麼? –
只是運行該程序來了解發生了什麼。 –
對不起,兄弟如果我的問題沒有定義好,當我運行這個程序時,我每次搜索一條記錄,它寫道「錯誤的用戶名或密碼再試一次」....這可以顯示編輯密碼本身,這是什麼我的意思是崩潰...程序寫得不好。首先,我搜索用戶名和密碼,我想編輯它的密碼,如果它找到了,那麼它允許我改變,它不會顯示此消息。但正如你所看到的,它在程序中的任何地方都會寫這個消息 –