Skip to content
Advertisement

How to create a void method for retire

whole qstn description Need help creating the retireplayer method in this assigmnent

Help needed to create avoid retireplayer method in the image attached above

This is my class so far

public class Cricket implements Sport { int[] playerIds = new int[11]; ;

public Cricket() {

    for (int i = 0; i < playerIds.length; i++) {
        playerIds[i] = 1;

    }
    System.out.println("A new cricket team has been formed");
}

@Override
public void calculateAvgAge(int[] age) {
    float sum = 0;
    for (int i = 0; i < age.length; i++) {
        sum = sum + age[i];
    }
    float avgAGE = sum / playerIds.length;
    System.out.println("The average age of the team is " + String.format("%.2f", avgAGE));


}

@Override
public void retirePlayer(int id) {
    boolean c = false;
    boolean k = false;
    for(int i = 0; i < playerIds.length; i++){

        playerIds[id] = -1;
        c = true;
        if(playerIds[i]==id){
            k =true;
        }

    }
    if(c) System.out.println("Player with id: "+ id + " has retired");
    if(k) System.out.println("Player already retired");









}

}

This was my initial code for the method Decptn: To create a retire player method(int id) assign -1 to playerid[id] which is my array used throught the whole class. i should print “player with id:{id} has retired” if the player has already retired i should print “Player already retired”

Advertisement

Answer

This runs through the array to find a matching id. if a match is found. it retires player and prints and returns the method. else if no match is found it prints no match found.

The problem with your code was that for each iteration of for loop, you assign each member of the array to -1, so you retired all players. You only retire the player if the id matches. That is what the if statement is for.

 public void retirePlayer(int id){
            for (int i=0; i<playerIds.length; i++) {
                if (playerIds[i] == id) {
                    playerIds[i] = -1;
                    System.out.println("The player with id: {"+id+"} has retired");
                    return;
                }
            }
    
            System.out.println("Player already retired");        
        }

//ignore above

public void retirePlayer(int id){
        //int id is an index!!
        if (id >11 || id < 1){
            System.out.println("Invalid player number!!");
            return;
        }
        if (playerIds[id-1] == 1) {
            playerIds[id-1] = -1;
            System.out.println("The player with id: {"+id+"} has retired");
        }else if (playerIds[id-1] == -1){
            System.out.println("Player already retired");
        }
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement