Java Program to find highest and second highestscores of students

Program:

Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the student with the highest score and the student with the second-highest score. Use the next() method in the Scanner class to read a name rather than using the nextLine() method. Assume that the number of students is at least 2.

Solution

import java.util.*;
public class Students {
    public static void main(String args[]) {
      Scanner sc= new Scanner(System.in);
  System.out.print("Enter the number of students:");
  int n = sc.nextInt();
  int large = 0;
  int secondlarge = 0;
  String name1 = "";
  String name2 = "";
 String name;
 int score=0;
  for (int i = 0; i < n; i++)
  {
     System.out.println("Enter a student name: ");
     name = sc.next();
     System.out.println("Enter a student score: ");
     score = sc.nextInt();

   if (score > large)
   {
    secondlarge = large;
    name2 = name1; 
    large = score;
    name1 = name;
   } 
   else if (score > secondlarge) {
    secondlarge = score;
    name2 = name;
   }

  }
  System.out.println("Top Two students: ");
  System.out.println(name1+" "+"score is"+large);
  System.out.println(name2+"score is " + secondlarge);
    }

}

No comments:

Post a Comment