In: Computer Science
Programming Java Homework:
Find the Highest Score (Just need the code and directions followed exactly and written in Java code)
Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the name and score of the student with the highest score.
Use the next () method in the Scanner class to read a name, rather than using the nextLine () method.
//importing package having Scanner class
import java.util.*;
//class
class Myclass
{
//main function
public static void main(String args[])
{
//n to store number of students
int n;
//array name for storing student names
String[] name;
//array scores for storing student marks
float[] scores;
//max to store max score
float max=0;
//variable j to store index of student name, score having highest
score
int j=0;
//creating input object of Scanner class
Scanner input=new Scanner(System.in);
//prompting the user to enetr number of students
System.out.print("Enter number of students: ");
//storing the input in n
n=input.nextInt();
//now allocating memory of n strings in name array
name= new String[n];
//now allocating memory of n float in scores array
scores=new float[n];
//loop which iterate to read n student names and their respective
scores
for(int i=0;i<n;i++)
{
//prompting user to enter student name
System.out.print("Enter name of student"+(i+1)+": ");
//storing user input name in name array at i index
name[i]=input.next();
//prompting user to enter student score
System.out.print("Enter score of student"+(i+1)+": ");
//storing score in scores array at index i
scores[i]=input.nextFloat();
}
//loop
for(int i=0;i<n;i++)
{
//if value at ith index of scores array is > max then
if(scores[i]>max)
{
//set max to that element
max=scores[i];
//set j to i
j=i;
}
}
//at the end of loop max is the highest value from scores array and
j is the index of that value
//display the name and score of the student with the highest
score
System.out.println("Student with the highest score "+max+" is
"+name[j]);
}
}