主要的Arrays.sort()错误

时间:2014-10-12 02:03:48

标签: java arrays sorting

所以我有一个程序可以测量用户的降雨量,并在一个只有基本的set / get mutators和accessors的Class RainFall的帮助下将它存储到一个数组中。我的问题是由于某种原因,程序在Arrays.sort()行崩溃。是否需要为该行创建一个新方法?如果是这样的话会是什么样子?

import java.util.Arrays;
import java.util.Scanner;
public class Lab7rain {

  public static void main(String[] args) {
    double amount=0;//VARIABLE DECLARATIONS
    RainFall r = new RainFall(amount);//CREATE OBJECT
    Scanner kb = new Scanner(System.in);//ALLOCATE SPACE
    RainFall[] month = new RainFall[12];

    for(int i=0; i<12; i++){
     System.out.println("What was the amount of rain in "+r.date()+"?");//rain per month
     amount = kb.nextDouble();//gets input
     month[i]= new RainFall(amount); //stores amount into array slot
     System.out.println();
     r.setTotal(amount);//sends amount to method that adds them together to create a total
    } 

    kb.close();

    r.setAvg();//initiates method that divides total by 12 to get average rain fall per month

    System.out.println(r.getTotal());//print total rain fall
    System.out.println(r.getAvg());//print average rain fall
    System.out.println();//skip line

    Arrays.sort(month);//i want this to sort the array so i can
    //then print out the highest and lowest months
    System.out.println(month[0]+" "+month[11]);
  }
}

线程中的异常&#34; main&#34; java.lang.ClassCastException:lab7rain.RainFall无法强制转换为java.lang.Comparable     at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)     在java.util.ComparableTimSort.sort(ComparableTimSort.java:157)     在java.util.ComparableTimSort.sort(ComparableTimSort.java:146)     在java.util.Arrays.sort(Arrays.java:472)     在lab7rain.Lab7rain.main(Lab7rain.java:46) Java结果:1

2 个答案:

答案 0 :(得分:3)

根据您在评论部分中的错误,您需要先在Comparable课程上实施RainFall界面,然后才能使用Arrays.sort()方法或使用Comparator正如 @ElliotFrisch 向您展示了答案。

public class RainFall implements Comparable<RainFall> {

    double amount;
    // your code

    public int compareTo(RainFall r) {
        return Double.compare(this.amount, r.amount); 
    }

}

答案 1 :(得分:2)

您的班级RainFall需要实施Comparable<RainFall>,或者您可以撰写Comparator<RainFall>并使用static class RainFallComparator implements Comparator<RainFall> { public int compare(RainFall a, RainFall b) { if (a.getAmount() < b.getAmount()) return -1; else if (a.getAmount() > b.getAmount()) return 1; return 0; } } 来获取该 Arrays.sort(month, new RainFallComparator()); 。例如,

{{1}}

然后

{{1}}