How to sort input from highest to lowest using Arrays in java? [closed]

て烟熏妆下的殇ゞ 提交于 2020-07-20 06:30:32

问题


I want to sort out the input which is name followed by the grades, I only want to sort out the grades

Sample input:

3 (limit) 
Hussain
 70
Omer
 60
User
 92

Sample Output:

User
 92
Hussain
 70
Omer
 60

Code:

import java.util.Scanner;
import java.util.Arrays;
public class Sortingofgrades{
 public static void main(String []args){
     Scanner keyboard = new Scanner (System.in);
     int num = keyboard.nextInt();
     String name[] = new String [num];
     int grade[] = new int [num];
        for (int x = 0; x < num; x++){
                name[x] = keyboard.nextLine();
                grade[x] = keyboard.nextInt();
                Arrays.sort(grade);
                    System.out.println(name[x]+grade[x]);
            }
        }
     
 }

回答1:


Your code sorted only grades but not names that goes with grades, so first person entered will have highest grade after sort even if it don't have actually, you need to sort names depending on their grades. First of all you should use custom class for this. Here is example:

class Person implements Comparable{
    String name;
    int grade;
    Person(String name,int grade){
        this.name=name;
        this.grade=grade;
    }

    public String getName() {
        return name;
    }

    public int getGrade() {
        return grade;
    }

    @Override
    public String toString() {
        return "Person [grade=" + grade + ", name=" + name + "]";
    }

    @Override
    public int compareTo(Object o) {
        return this.grade-((Person)o).getGrade();
    }
    
}

After that you create some Persons with name and grade, then sort it like this:

public class Test{
    public static void main(String[] args) {
        List<Person> persons=new ArrayList<>();
        persons.add(new Person("Person 1", 65));
        persons.add(new Person("Person 2", 84));
        persons.add(new Person("Person 3", 79));
        Collections.sort(persons,Collections.reverseOrder());
        System.out.println(persons);
    }
}



回答2:


Arrays.sort(grade, Collections.reverseOrder())

This will sort your array in descending order (highest to lowest).

As an alternative, you can also use Collections.sort() as such:

Collections.sort(grade, Collections.reverseOrder())



来源:https://stackoverflow.com/questions/62616620/how-to-sort-input-from-highest-to-lowest-using-arrays-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!