在Java中为每次尝试添加结果

时间:2018-01-15 21:30:23

标签: java

我对Java完全陌生,需要一些帮助。我试图在比赛中为每次尝试添加结果但是我被卡住了。到目前为止,我的第一部分工作但没有添加任何结果,然后我试图找到一种方法来添加结果,同时计算允许的尝试(每个学科不同),但没有成功。什么是计算尝试和为每次尝试添加结果的最佳方法?`

private void addResult() {

    System.out.print("Enter the number of the participant you would like to add results for: ");
    int number = scan.nextInt();
    scan.nextLine();

    while (number < 0) {  
        System.out.println("Error: must be greater than or equal to zero!");
        number = scan.nextInt();
        scan.nextLine();
     }
System.out.print("Enter the name of the event you would like to see results for: ");
String event = scan.nextLine();

Participant p = findParticipantByNumber(number);
Event e = findEventByName(event);

if (p == null) {
    System.out.println("No participant with number " + number + " found!");

    } else if (e == null) {
        System.out.println("No event called " + event + " found!");
    } else {

         System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
         " from " + p.getTeam() +
         " in " + e.getEventName() + ":" + " " + p.getResult() ); 
         scan.nextLine(); 
         Result r = new Result(e, p);
         p.addResult(r);

    }
}

1 个答案:

答案 0 :(得分:0)

我会在参与者类中存储尝试的HashMap作为实例变量,其中键是表示事件的字符串,每个键对应的值是到目前为止该事件的尝试次数。您可以在参与者中调用此地图attemptsByEvent并使用getter和setter方法。如果需要,您可以查看TutorialsPoint中的this page,了解如何创建和填充地图,以及它们是什么。

您还应该创建一个可以从addResult()中访问的映射,该映射具有将事件表示为键的字符串以及该事件作为值的最大允许尝试次数。您可以将此地图称为attemptMaximums

然后,您可以修改最后一段代码,以便在添加结果之前检查目前为止的尝试次数。如果您确实为尝试添加了结果,则还应增加参与者地图中的值。

else {
     System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
         " from " + p.getTeam() +
         " in " + e.getEventName() + ":" + " " + p.getResult() ); 
     scan.nextLine(); 
     Result r = new Result(e, p);
     int attempts = p.getAttemptsByEvent().get(e);
     if(attempts < attemptMaximums.get(e)){
         p.addResult(r);
         p.getAttemptsByEvent().put(e, attempts+1);
     }
}