替换java文本文件中的单词
我的代码在这里:替换java文本文件中的单词,java,arrays,file-handling,Java,Arrays,File Handling,我的代码在这里: 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=ne
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
正如您所见,我将info/line设置为数组,这样它就可以读取索引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)
线程“main”java.lang.NullPointerException中的异常
位于java.util.regex.Pattern。(未知源)
位于java.util.regex.Pattern.compile(未知源代码)
位于java.util.regex.Pattern.matches(未知源)
at java.lang.String.matches(未知源)
在lozada.My_Voting_System_Official.Edit(My_Voting_System_Official.java:135)
在lozada.My\u Voting\u System\u Official.Menu(My\u Voting\u System\u Official.java:43)
在lozada.My\u Voting\u System\u Official.main(My\u Voting\u System\u Official.java:15)
我认为您没有声明oldName变量 在此代码中
if(信息[1]。匹配(旧名称)){
outFile.append(信息[1]=新名称);
outFile.close();
}
请包含堆栈跟踪。您从代码中的哪一行获得NPE?另外,使用equals
或equalsIgnoreCase
而不是匹配
检查其常规字符串。@Veluria i已经添加了它:)@Sachin i(思考)我添加了一行代码,其中有一行出错,呵呵:)vNumForEdit和oldName没有声明。我的大多数变量都是全局声明的:)堆栈trance则相反。“Unknown Source”在该行放置断点,运行调试程序代码,然后查看是否声明了oldName。使用。等于