【发布时间】:2021-03-23 11:04:31
【问题描述】:
我正在尝试制作一个能够添加新参与者并将其保存在 txt 文件中的程序。该程序还能够从 txt 文件中读取数据并进行处理。该程序可以运行,但是当我尝试按状态显示参与者时。我得到 java.lang.ClassCastException : java.lang.String cannot be cast to Reading 。尝试了几件事,但仍然无法弄清楚
import java.util.* ;
import java.io.* ;
class KRBApp{
public static int menu(){
Scanner sc = new Scanner(System.in);
System.out.println("\n\n\n\t\t\tKRB APPLICATION MAIN MENU");
System.out.println("\t\t\t~~~~~~~~~");
System.out.println("\n\t\t\t1. Add new participant");
System.out.println("\t\t\t2. Display participants by state");
System.out.println("\t\t\t3. Search participants by name");
System.out.println("\t\t\t4. Exit");
System.out.print("\n\t\t\t>>> ");
int ch = Integer.parseInt(sc.nextLine());
return ch;
}//menu
public static void main(String []args)throws FileNotFoundException, IOException{
Scanner sc = new Scanner(System.in);
ArrayList pList = new ArrayList();
FileReader fr1 = new FileReader("data.txt");
BufferedReader br1 = new BufferedReader(fr1);
String read= br1.readLine();
while(read!= null){ //read file io
StringTokenizer st = new StringTokenizer(read,";");
String name = st.nextToken();
String phone = st.nextToken();
String ic = st.nextToken();
Reading reading = new Reading(name,phone,ic);
pList.add(read);
read = br1.readLine();
}//while
Reading reading = null;
File fi1 = new File("data.txt");
FileWriter fw1 = new FileWriter(fi1,true);
BufferedWriter bw1 = new BufferedWriter(fw1);
PrintWriter pw1 = new PrintWriter(bw1);
int ch = 0;
do{
ch = menu();
if(ch == 1){ // add new participant
System.out.print("Enter Name : ");
String name = sc.nextLine();
System.out.print("Enter Phone Number : " );
String noTel = sc.nextLine();
System.out.print("Enter IC Number : ");
String noIC = sc.nextLine();
System.out.println(); //new line for each data
Participant pt = new Participant( name,noTel,noIC);
pw1.println(pt.toFile());
}
else if(ch == 2){ // search by state
for(int i = 0; i < pList.size() ; i++){
reading = (Reading)pList.get(i); // error here
System.out.print(reading.getName());
}
}
else if(ch == 3){ //sort by name
//call method ...
}
}while(ch != 4);
System.out.print("\n\n\n\t\t\tThank You and See You Again! ");
//close
pw1.close();
}//public
}//class
读取类从文件io读取数据
class Reading {
private String name;
private String phone;
private String ic;
public Reading ( String name , String phone , String ic ){
this.name = name;
this.phone = phone;
this.ic = ic;
}
public String getName() { return name;}
public String getPhone() {return phone;}
public String getIc() { return ic; }
public String displayAll(){
return "Name : "+ name + "\n" + "Phone numbers : " +phone + "\n" + "Ic : " +ic + "/n" ;
}
}//class
这里Participant类用来发送数据到文件io
class Participant {
private String name;
private String noTel;
private String noIC;
public Participant ( String name , String noTel , String noIC ){
this.name = name;
this.noTel = noTel;
this.noIC = noIC;
}
public String toFile(){
return name+";"+ noTel + ";" + noIC ;
}//toFile
}//class
【问题讨论】:
-
注意警告。