我正在学习大学生,所以我需要你的帮助来解决这个问题。 我在student.txt文件中混合了UG_Student和GradStudent。
Jane Jones;111999;11 First St, Unitown,2999;0401 444 444;4483;4;6;7
Peter Smith;111998;22 Second St, West,5999;999 777;B Sc;2000;4672;5;5;5
Jim Smith;111988;25 Third St, South,6001;0412 222 333;BESE;1998;4672;4;5;5
John William;334344;123 Fig St, Townville,5655;0404 333 333;4333;5;6;5
第一行和最后一行按此顺序有数据,表示UG_Student:
Name;StudentID;Address; ContactNo;SubjectNo;Test1;Test2;Test3
第二行和第三行按此顺序有数据,表示GradStudent:
Name;StudentID;Address; ContactNo;PreviousDegree;GradYr;SubjectNo;Test1;Test2;Test3
如果txt文件包含UG_Student或GradStudent,我有以下只能在JTextarea上读取和打印的代码。
public void openFile()
{
try
{
input = new Scanner( new File("student.txt"));
input.useDelimiter(";");
}
catch ( FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file.");
System.exit(1);
}
}
public String readFile()
{
Student ugStudent = new UGstudents();
Student gradStudent = new Gradstudents();
//int lineNumber = 1;
//System.out.printf("running...");
try
{
while ( input.hasNext() )
{
String name = ugStudent.name = input.next();
int studentID = ugStudent.studentID = input.nextInt();
String address = ugStudent.address = input.next();
int contactNo = ugStudent.contactNo = input.nextInt();
int subjectNo = ugStudent.subjectNo = input.nextInt() ;
int test1 = ugStudent.test1 = input.nextInt();
int test2= ugStudent.test2 = input.nextInt();
int test3= ugStudent.test3 = input.nextInt();
String checkGrade= ugStudent.checkGrade();
//System.out.println(name + studentID + address + contactNo + subjectNo + test1 + test2 + test3 + checkGrade);
resultColumn = ("Name\t Student Id\t Address\t\t Contact No\t Subject No\t Test 1\t Test 2\t Test 3\t Grade\n--------------------------------------------------------------------------------------------------------------------\n");
result+=(name+ "\t" + studentID + "\t " + address + "\t " + contactNo + "\t " + subjectNo + " \t" + test1 + "\t " + test2 + "\t " + test3 + "\t " + checkGrade);
}
}
catch ( NoSuchElementException elementException)
{
System.err.println( "File improperly formed." );
input.close();
System.exit( 1 );
}
catch ( IllegalStateException stateException )
{
System.err.println( "Error reading from file." );
System.exit( 1 );
}
return resultColumn +result;
}
public void closeFile()
{
if ( input != null )
input.close();
}
}
但是,给定的文本文件应包含如上所示的数据混合。我的问题是,如何从该文本文件中只读取和打印UG_Student或GradStudent数据?抱歉很长的问题,但这是我能做的最好的。
答案 0 :(得分:0)
在我看来,你最好的选择是使用正则表达式。您可以为每种类型的行添加表达式,并尝试匹配每一行,跳过那些不适用的行。例如:
Pattern undergrad = Pattern.compile("(\\w*) (\\w*);(\\d*); ...");
Matcher matcher = undergrad.match(line);
if (matcher.matches()) {
String firstName = matcher.group(1);
String secondName = Matcher.group(2);
String studentNumber = Matcher.group(3);
...
}
使用正则表达式的优点是您匹配该行并识别要在单个指令中提取的值。有关其使用的详细信息,请参阅Pattern。