Finding the best person in an array
I have an array called Names[5] and one called scores[5][5]. Each row corresponds with the name in the respective index.
I need to find the highest score in the scores array and return the name that corresponds with it.
This is what I have so far开发者_JS百科:
int high = 0;
for(a=0; a<5; a++)
for(b=0; b<5; b++)
if(high<scores[a][b])
Just scan the matrix, and remember the best score and best name so far. Something like:
String[] names = {"a","b","c","d","e"};
int[][] scores = new int[5][5];
//... init scores
int best = Integer.MIN_VALUE;
String bestName = null;
for(int nm = 0;nm<5;nm++){
for(int c = 0;c<5;c++){
int score = scores[nm][c];
if (score>=best){
best = score;
bestName = names[nm];
}
}
}
System.out.println(bestName);
精彩评论