我正在完成家庭作业并且卡住了。
列表运行者应该在结尾显示跑步者的名字以及他们所在的年龄组,如初级,高级等。
我只是在将ageGroup排序到排名后如何获取值时感到困惑,任何小指针都会受到赞赏。如果有帮助,请使用BlueJ
。
import java.util.*;
import java.io.*;
import ou.*;
/**
* Write a description of class MarathonAdmin here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class MarathonAdmin
{
// instance variables - replace the example below with your own
private Runner runners;
List<String> runner = new ArrayList<String>();
/**
* Constructor for objects of class MarathonAdmin
*/
public MarathonAdmin()
{
// initialise instance variables
List<String> runner = new ArrayList<String>();
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public void readInRunners()
{
// put your code here
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
BufferedReader bufferedFileReader = null;
try
{
String runnerLine;
String ageGroup;
Scanner runScanner;
bufferedFileReader = new BufferedReader(new FileReader(aFile));
runnerLine = bufferedFileReader.readLine();
while(runnerLine != null)
{
runScanner = new Scanner(runnerLine);
runScanner.useDelimiter(",");
runnerLine = runScanner.next();
ageGroup = runScanner.next();
for (String run : runner)
if (Integer.parseInt(ageGroup) < 18)
{
System.out.println(runnerLine + " : Junior");
}
if (Integer.parseInt(ageGroup) > 55)
{
System.out.println(runnerLine + " : Senior");
}
if (Integer.parseInt(ageGroup) > 18 && Integer.parseInt(ageGroup) < 55)
{
System.out.println(runnerLine + " : Standard");
}
this.runners = new Runner();
runner.add(runnerLine);
runner.add(ageGroup);
runnerLine = bufferedFileReader.readLine();
}
}
catch (Exception anExpection)
{
System.out.println("Error: " + anExpection);
}
finally
{
try
{
bufferedFileReader.close();
}
catch(Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
}
答案 0 :(得分:0)
如果我以正确的方式理解你的问题,这是解决问题的一种方法:
HashMap<String, ArrayList<String>> ageGroups = new HashMap<String, ArrayList<String>>();
ageGroups.put("Junior", new ArrayList<String>());
ageGroups.put("Senior", new ArrayList<String>());
ageGroups.put("Standard", new ArrayList<String>());
for (String run : runner) {
if (Integer.parseInt(ageGroup) < 18) {
ageGroups.get("Junior").add(run);
System.out.println(runnerLine + " : Junior");
}
if (Integer.parseInt(ageGroup) > 55) {
System.out.println(runnerLine + " : Senior");
ageGroups.get("Senior").add(run);
}
if (Integer.parseInt(ageGroup) > 18 && Integer.parseInt(ageGroup) < 55) {
System.out.println(runnerLine + " : Standard");
ageGroups.get("Standard").add(run);
}
}
稍后获取某个组的所有参赛者,您只需致电:
ArrayList<String> seniors = ageGroups.get("Senior")
我使用HasMap的原因是你现在可以轻松处理所有类的跑步者,特别是如果你添加更多的组/类。
编辑:之后我现在可以看到,这很多都不是你想要的地方,但我会留下它,因为它仍然有用。