对于你们许多人来说,这是一个简单的问题,但我仍然无法在一段时间后解决它。 我想读下面的文本文件,并执行排序并显示出来。
部分“HELP”应该是学生的显示乐队,但经过多次尝试我无法生成。
public class gradesorting {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("grades.txt"));
List<String> grades = new ArrayList<String>();
List<String> banding = new ArrayList<String>();
List<String> student = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null)
{
String[] lines = line.split(":");
if (lines[0].equals("Student"))
{
Pattern p = Pattern.compile("(?:([^:]*):(\\d*):)");
Matcher m = p.matcher(line);
while(m.find()) {
int i=1;
String name = m.group(i);
int grade = new Integer(m.group(i+1));
System.out.println("Student with Grade "+ "HELP" + " and Band " + grade + " are," +name);
}
}
if (lines[0].equals("Band"))
{
Pattern p = Pattern.compile("(?:([^:]*):(\\d*):)");
Matcher m = p.matcher(line);
while(m.find()) {
int i=1;
String grade = m.group(i);
int band = new Integer(m.group(i+1));
System.out.println("Grade "+ grade + " equal Band " + band);
}
}
grades.add(line);
banding.add(line);
student.add(line);
}
reader.close();
}
}
读入文本文件
(this is only part of the text file)
there will be more lines of students)
Grade:1:2:3:4:5:
Band:D:1:A:2:B:3:C:4:
Student:Fiona:2:Cindy:1:Alyssa:4:
Student:Wendy:4:
我在控制台中的当前输出..
Grade D equal Band 1
Grade A equal Band 2
Grade B equal Band 3
Grade C equal Band 4
Student with Grade HELP and Band 2 are,Fiona
Student with Grade HELP and Band 1 are,Cindy
Student with Grade HELP and Band 4 are,Wendy
理想输出
Grade D equal Band 1
Grade A equal Band 2
Grade B equal Band 3
Grade C equal Band 4
Student with Grade D and Band 1 are, Cindy
Student with Grade A and Band 2 are, Fiona
Student with Grade C and Band 4 are, Wendy
Student with Grade C and Band 4 are, Alyssa
答案 0 :(得分:0)
您必须在年级和乐队之间在java中建立连接。我使用了hashMap。
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("grades.txt"));
HashMap<Integer, String> map = new HashMap<Integer,String>();
List<String> grades = new ArrayList<String>();
List<Integer> banding = new ArrayList<Integer>();
String line;
while ((line = reader.readLine()) != null)
{
String[] lines = line.split(":");
if (lines[0].equals("Student"))
{
Pattern p = Pattern.compile("(?:([^:]*):(\\d*):)");
Matcher m = p.matcher(line);
while(m.find()) {
int i=1;
String name = m.group(i);
int grade = new Integer(m.group(i+1));
System.out.println("Student with Grade "+ map.get(grade) + " and Band " +
grade + " are," +name);
}
}
if (lines[0].equals("Band"))
{
Pattern p = Pattern.compile("(?:([^:]*):(\\d*):)");
Matcher m = p.matcher(line);
while(m.find()) {
int i=1;
String grade = m.group(i);
int band = new Integer(m.group(i+1));
System.out.println("Grade "+ grade + " equal Band " + band);
map.put(band, grade);
}
}
}
reader.close();}}