2016-02-28 73 views
2

我有我的代碼在這裏:替換文本文件中的Java一句話

public void Edit()throws IOException{ 
     FileWriter writeFile=new FileWriter("voters.txt", true); 
     BufferedWriter outFile=new BufferedWriter(writeFile); 
     File readFile=new File("voters.txt"); 
     BufferedReader read=new BufferedReader(new FileReader(readFile)); 

     vNumForEdit=JOptionPane.showInputDialog("Enter voters number: "); 
     String line=null; 
     while((line=read.readLine())!=null){ 
      String [] info=line.split("/"); 
      if(info[0].matches(vNumForEdit)){ 
       String [] forEditMenu={"Name", "Age", "Gender", "Date of Birth", "Place of Birth", "Address", "Civil Status", "Citizenship", "Profession/Occupation", "Father's Name", "Mother's Name"}; 
       forEdit=(String)JOptionPane.showInputDialog(null, line+"\n\nPlease select what you want to edit", "National Election 2765", 1, null, forEditMenu, forEditMenu[0]); 
       switch(forEdit){ 
       case "Name": 
        newName=JOptionPane.showInputDialog("Enter new name: "); 
        if(info[1].matches(oldName)){ 
         outFile.append(info[1]=newName); 
         outFile.close(); 
        } 
        read.close(); 

        break; 
       } 
      } 
     } 
    } 

文本文件看起來像這樣

1/d/19/Male/e//s/Single/v/e/e/f 
2/c/98/Male//d/c/Single/r/w/q/d 

,你可以看到我發的信息/線陣列,它可以讀取作爲投票號碼的索引0中的值。任務是用戶將輸入選民號碼,然後如果發現,用戶將再次輸入他想要編輯的內容。我使用數組以及確定的姓名,年齡,性別等數組是這樣的:

info[0] = voters number 
info[1]= name 
info[2] = age 
info[3] = date of birth 
info[4]= place of birth 
info[5] = status 
info[6] = citizenship 
info[7] = profession 
info[8] = father's name 
info[9] = mother's name 

,但我的代碼總是錯誤java.lang.NullPointerException結束。我大部分的變量有全局聲明

編輯:這裏的錯誤/堆棧跟蹤

Exception in thread "main" java.lang.NullPointerException 
    at java.util.regex.Pattern.<init>(Unknown Source) 
    at java.util.regex.Pattern.compile(Unknown Source) 
    at java.util.regex.Pattern.matches(Unknown Source) 
    at java.lang.String.matches(Unknown Source) 
    at lozada.My_Voting_System_Official.Edit(My_Voting_System_Official.java:135) 
    at lozada.My_Voting_System_Official.Menu(My_Voting_System_Official.java:43) 
    at lozada.My_Voting_System_Official.main(My_Voting_System_Official.java:15) 
+1

請包括堆棧跟蹤。 – Veluria

+0

代碼中的哪一行會得到NPE? – Sachin

+1

此外,如果檢查其常規字符串是否使用「equals」或「equalsIgnoreCase」而不是「matches」。 – Sachin

回答

0

我想你沒有申報的使用oldName變量 在此代碼

if(info[1].matches(oldName)){ 
 
         outFile.append(info[1]=newName); 
 
         outFile.close(); 
 
        }

+0

vNumForEdit和oldName未聲明。 –

+0

我的大部分變量都是全局聲明的:) – bruh

+0

以及堆棧恍惚說不然。 「Unknown Source」 –