Day 5 - Java

Problem Statement:

You are given a list of students with their names and marks. Sort the students based on their marks in descending order and print the sorted list.

Input Format:

The first line of input contains an integer N (1 ≤ N  ≤ 10^3), denoting the number of students.

Following  N lines contain the name and marks of each student separated by a space.

Output Format:

Print the names and marks of the students sorted in descending order of marks.

Constraints:

Each student name consists of only alphabets and has a maximum length of 100 characters.

Marks of students range from 0 to 100.

Instructions:

Read the number of students 

N from the input.

For each of the N students, read their name and marks separated by a space.

If the input format is invalid (i.e., does not contain exactly two elements per line), throw Exception.

Create an array of  N Student objects where each object stores the name and marks of a student.

Sort the array of students in descending order of marks using the Comparable interface.

Print the sorted list of students, each on a new line, displaying the name and marks separated by a space.

Sample Input:

Raina 90

Virat 85

Jaddu 75

Dhoni 95

Rutu 80

Sample Output:

Dhoni - 95

Raina - 90

Virat - 85

Rutu - 80

Jaddu - 75

Note:

Ensure that your program adheres to the specified input and output format.

Use the Comparable interface to implement the comparison logic for sorting the Student objects.

Utilize the Stream API's sorted() method to sort the array of students.

Handle any potential input errors, such as invalid input format or out-of-range marks.

Error Cases:

#1

3

A 90

B 85 75

C 101

Invalid input: Invalid input format.


#2

4

A 90

B 85

C -5

D 80

Invalid input: Marks should be between 0 and 100.


SOLUTION

import java.util.Arrays;

import java.util.Scanner;


class Student implements Comparable<Student> {

    private String name;

    private int marks;


    public Student(String name, int marks) {

        this.name = name;

        this.marks = marks;

    }


    public String getName() {

        return name;

    }


    public int getMarks() {

        return marks;

    }


    @Override

    public int compareTo(Student other) {

        return Integer.compare(other.marks, this.marks);

    }


    @Override

    public String toString() {

        return name + " - " + marks;

    }

}


public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);


        try {

            int numberOfStudents = scanner.nextInt();

            scanner.nextLine();


            Student[] students = new Student[numberOfStudents];


            for (int i = 0; i < numberOfStudents; i++) {

                String[] input = scanner.nextLine().split("\\s+");

                if (input.length != 2) {

                    throw new IllegalArgumentException("Invalid input format.");

                }

                String name = input[0];

                int marks = Integer.parseInt(input[1]);

                if (marks < 0 || marks > 100) {

                    throw new IllegalArgumentException("Marks should be between 0 and 100.");

                }

                students[i] = new Student(name, marks);

            }


            Arrays.stream(students)

                    .sorted()

                    .forEach(System.out::println);

        } catch (Exception e) {

            System.out.println("Invalid input: " + e.getMessage());

        } finally {

            scanner.close();

        }

    }

}


Insights:
  • The Student class implements the Comparable<Student> interface. This allows instances of Student to be compared based on their marks, enabling sorting operations.
  • The compareTo method is overridden in the Student class to define the natural ordering of Student objects based on their marks in descending order.
  • An array of Student objects is created to store the student data obtained from user input. Each element of the array represents a student.
  • The program utilizes the Stream API to sort the array of Student objects in descending order based on marks. It then prints the sorted list of students using method references.
  • Always validate user input to ensure it meets expected criteria (e.g., correct format, within acceptable range).
  • Follow encapsulation principles by providing getter and setter methods to access and modify class attributes.
  • Test the program with various input scenarios, including edge cases and invalid inputs, to ensure robustness.
Explore:

To sort an Array in descending order using Stream API

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        int[] arr = {6, 3, 9, 18, 7};
        
        Arrays.stream(arr)
              .boxed() 
              .sorted(Comparator.reverseOrder())
              .forEach(System.out::println);
    }
}

Happy Coding!! :)

Comments