// i need help with this program below. i have to organize the top scores that a
ID: 3836090 • Letter: #
Question
// i need help with this program below. i have to organize the top scores that are listen within the program, the scores are in the line that reads int [] grades = {78, 88, 97, 75, 82, 63, 91}; it has to be written in java programming and the software that im using is dr java
public class Scores {
private int [] scores;
Scores(int [] grades) {
scores = new int[grades.length];
for (int i = 0; i < grades.length; i++) {
scores[i] = grades[i];
}
}
public int getTopScore() {
// Your code here
}
}
public class TopScore {
public static void main(String [] args) {
int [] grades = {78, 88, 97, 75, 82, 63, 91};
Scores sc = new Scores(grades);
int top = sc.getTopScore();
System.out.println("Top score is " + top);
}
}
Explanation / Answer
Source Code:
public class Scores {
private int [] scores;
Scores(int [] grades) {
scores = new int[grades.length];
for (int i = 0; i < grades.length; i++) {
scores[i] = grades[i];
}
}
public int getTopScore() {
// Your code here
int topScore = scores[0];
for(int i=1; i<scores.length; i++)
{
if(scores[i] > topScore)
{
topScore = scores[i];
}
}
return topScore;
}
}
public class TopScore {
public static void main(String [] args) {
int [] grades = {78, 88, 97, 75, 82, 63, 91};
Scores sc = new Scores(grades);
int top = sc.getTopScore();
System.out.println("Top score is " + top);
}
}
Output:
Top score is 97
Description:
So, here you require a method that is returning the maximum number from all the numbers given in grades[ ] array.
These values are stored in member array scores[ ] for all object of class Scores and so inside the class method getTopScore().
So, in this method, at first I am defining the integer variable topScore and assigning it the value of first element of array.
Now, starting from second array element of array i.e. index i=1 to its length I am checking that if the value at that index is greater than previously found value or not.
If it is such, I am setting that value as new topScore and this loop will check with that new value. So, at the end of the loop, the top score is stored in that variable.
So at the end I am returning that value and see the output line I got. It is giving the correct output.
So this is the code you had asked for..
Do comment if there is any query. Thank you. :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.