create method
parameters: string array and integer variable
return: integer variable max
method will receive a string array containing scores for a single day and return the id of the player with maximum score
For a day “12,0-234,1-23,3-201,2-1”. The array would be arr [0] is a string “12”
arr [1] is“0-234”arr [2] is“1-23”arr [3] is“3-201” arr [4] is“2-1”
assume ply.txt file is used
While the first element is game points for that day, other elements are player id and their score for the day.Using a loop,we need to process each players score.We will extract the player id and their score (string indexOf, substring and Integer.parseInt). After finding it, it should place the score for player in a temporary array for players. Then it should find the id of player with highest scores.
For this, create a temporary array Scores and store score of player 0 in Scores[0], score of player 1 in Score[1] and so on.
This method will return max as the id of the playerwith highest score for the data of day in inputarray arr.
public class Main {
public static int findMax(String[] dayScores, int players) {
int max = Integer.MIN_VALUE;
int id = -1;
int[] scores = new int[dayScores.length - 1];
for (int i = 1; i < dayScores.length; i++) {
String[] player = dayScores[i].split("-");
scores[Integer.parseInt(player[0])] = Integer.parseInt(player[1]);
}
for (int i = 0; i < scores.length; i++) {
if (scores[i] > max) {
max = scores[i];
id = i;
}
}
return id;
}
public static void main(String[] args) {
System.out.println(findMax(new String[]{"12","0-234","1-23","3-201","2-1"}, 3));
}
}
Comments
Leave a comment