java对输入的数组排序,如何使用Java中的数组将输入从最高到最低排序?

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]);

}

}

}

解决方案

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 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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值