我正在嘗試創建一個電話目錄,用戶必須使用 JTextField 在其中輸入多個輸入。我還有一個搜索選項,可以從 filewriter 的目錄中搜索輸入的名稱,但我似乎無法將我的輸入存盤在 filewriter 中。這是我的初始代碼
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int menu = 0;
boolean quit = false;
do{
String input = JOptionPane.showInputDialog(null,"Telephone Directory Management System"
"\n1. Add a Student"
"\n2. Search"
"\n3. Sort Data"
"\n4. List of all data"
"\n5. Exit"
"\n\nPlease enter your choice:","Main Menu",JOptionPane.QUESTION_MESSAGE);
menu = Integer.parseInt(input);
switch (menu) {
case 1:
JTextField student = new JTextField();
JTextField name = new JTextField();
JTextField address = new JTextField();
JTextField phone = new JTextField();
Object[] fields = {
"Enter Student ID:",student,
"Enter Name:",name,
"Enter Address:",address,
"Enter Phone No.:",phone};
int add = JOptionPane.showConfirmDialog(null,fields,"Add a Student",JOptionPane.OK_CANCEL_OPTION);
if (add == JOptionPane.OK_OPTION)
{
String student1 = student.getText();
String name1 = name.getText();
String address1 = address.getText();
String phone1 = phone.getText();
FileWriter fw = new FileWriter(new File("directory.txt"), true);
BufferedWriter out = new BufferedWriter(fw);
out.write(student1 " " name1 " " address1 " " phone1);
out.newLine();
}
break;
case 2:
input = JOptionPane.showInputDialog(null,"Enter name to search information:","Search",JOptionPane.OK_CANCEL_OPTION);
File f = new File("directory.txt");
try {
BufferedReader freader = new BufferedReader(new FileReader(f));
String s;
while ((s = freader.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String nm = st[1];
String add1 = st[2];
String phoneNo = st[3];
if (input.equals(nm)) {
JOptionPane.showMessageDialog(null,"Student ID: " id "\nName: " nm "\nAddress: " add1 "\nPhone No.: " phoneNo "","Information",JOptionPane.QUESTION_MESSAGE);
}
}
freader.close();
} catch (Exception e) {
}
break;
我之前嘗試過使用掃描儀,它確實存盤了我的輸入,但我需要在這個中使用 JOptionPane。非常感謝任何可以幫助我的人。
uj5u.com熱心網友回復:
你應該在寫入后關閉 BufferedWriter,就像這樣
out.close()
如果您不這樣做,BufferedWriter 不會將您寫入其中的內容重繪 到底層流中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/343767.html
