Arrays.sort()给出以下错误:

FiveDice.java:19: error: no suitable method found for sort(int)
   Arrays.sort(compNums);


如果我从for循环中取出任何东西,它会认为您只有1个数字或给出错误。还有哪些其他排序选项可用?

import java.util.*;
public class FiveDice {
    public static void main(String[] args) {
        int x;
        int compNums = 0;
        int playerNums;

        Die[] comp = new Die[5];
        Die[] player = new Die[5];
        System.out.print("The highest combination wins! \n5 of a kind, 4 of a kind, 3 of a kind, or a pair\n");
//computer
        System.out.print("Computer rolled:  ");
        for(x = 0; x < comp.length; ++x) {
            comp[x] = new Die();
            compNums = comp[x].getRoll();
           //Arrays.sort(compNums); <--does not work
           System.out.print(compNums + " ");
        }
//player
        System.out.print("\nYou rolled: \t  ");
        for(x = 0; x < player.length; ++x) {
            player[x] = new Die();
            playerNums = player[x].getRoll();
            System.out.print(playerNums + " ");
        }
    }
}


死班

public class Die {
    int roll;
    final int HIGHEST_DIE_VALUE = 6;
    final int LOWEST_DIE_VALUE = 1;
    public Die()
       {   }
    public int getRoll() {
        roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
        return roll; }
    public void setRoll()
        { this.roll = roll; }


}

最佳答案

您不必使用2个数组进行排序。如果实现Comparable<T>接口,则可以通过Java Collections API对类进行排序。在您的情况下,Die类可以实现Comparable<T>并为Java框架提供一种比较骰子值的方法。

看一下Java API:
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

在您的情况下:

public class Die implements Comparable<Die>{

    int roll;
    final int HIGHEST_DIE_VALUE = 6;
    final int LOWEST_DIE_VALUE = 1;

    public Die() {   }

    public int computeRoll() {
        roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
        return roll;
    }

    // I also changed this to store the value
    public int getRoll() {
        return roll;
    }
    public void setRoll() { this.roll = roll; }

    // This is the method you have to implement
    public int compareTo(Die d) {
        if(getRoll() < d.getRoll()) return -1;
        if(getRoll() > d.getRoll()) return +1;
        if(getRoll() == d.getRoll()) return 0;
    }

}


只要您拥有Dies的Collection,例如ArrayList或LinkedList,就可以对集合本身进行排序。下面是示例代码。

ArrayList<Die> myCollection = new ArrayList<Die>();
myCollection.add(die1);
// more array population code
// ...
Collections.sort(myCollection);

09-30 15:33
查看更多