Answer to Question #123900 in Java | JSP | JSF for Shouzab

Question #123900
Write Java program to
a. Accept names and marks of 10 students from user
b. Ensure that valid data is entered. If user enters an invalid data then appropriate message should be displayed, e.g. “Name cannot be a number” or “Marks must be an integer value”
c. Display this data in descending order according to the marks such that name of the student having maximum marks should be displayed at the top and the name of the student having minimum marks should be displayed at the bottom.
1
Expert's answer
2020-06-29T08:20:52-0400
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[10];
        Scanner in = new Scanner(System.in);
        String s, name;
        int mark;
        int i = 0;
        while (i<10) {
            try {
                s = in.nextLine();
                if (s.split(" ").length == 2) {
                    name = s.split(" ")[0];
                    mark = Integer.parseInt(s.split(" ")[1]);
                    for (int j = 0; j < name.length(); j++) {
                        if (!Character.isAlphabetic(name.charAt(j))) {
                            throw new InputMismatchException("Name cannot be a number or include other chars except Aa-Zz");
                        }
                    }
                    if(mark>0){
                        students[i] = new Student(name, mark);
                        i++;
                    }else{
                        throw new InputMismatchException("Mark cannot be negative");
                    }
                } else {
                    throw new InputMismatchException("Enter 2 data: name and mark");
                }

            } catch (NumberFormatException e) {
                System.out.println("Marks must be an integer value");
            } catch (InputMismatchException e) {
                System.out.println(e.getMessage());
            }
        }
        Arrays.sort(students);
        for (int j = students.length-1; j >=0 ; j--) {
            System.out.println(students[j]);
        }
    }
}

class Student implements Comparable<Student> {
    private String name;
    private int mark;

    Student(String name, int mark) {
        this.name = name;
        this.mark = mark;
    }

    public int getMark() {
        return mark;
    }

    @Override
    public int compareTo(Student o) {
        return mark - o.getMark();
    }

    @Override
    public String toString() {
        return "Name: "+name+", Mark: "+mark;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS