好的,我想出了如何制作GUI类和排序类,但似乎可以弄清楚如何实现类比的类。我需要创建随机大小的矩形,然后将它们排序。感谢任何帮助再次感谢。
import java.util.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoSorts extends Applet implements ActionListener
{
private final int APPLET_WIDTH = 600;
private final int APPLET_HEIGHT = 600;
Button sort;
Label sort_label;
String pr_name;
int[] random = new int[20];
int[] sorter = new int[20];
public void init()
{
sort = new Button("Sort");
add(sort);
sort.addActionListener(this);
sort_label = new Label("Orange Selection / Black Bubble");
add(sort_label);
randomGen(random);
sorter = random;
setBackground (Color.white);
setSize (APPLET_WIDTH, APPLET_HEIGHT);
}
private void randomGen (int...random) {
for (int i = 0; i < 20; i++){
random [i] = (int) (20 +(Math.random()*300-20));
}
}
public void paint(Graphics g)
{
for (int i = 0; i < 20; i++ ){
g.setColor(Color.blue);
g.fillRect((int) (10 + (i*50)), 300, 50, ((random[i])));
g.setColor(Color.black);
g.fillRect((int) (10 + (i*50)), 300, 25, (sorter[i]));
}
g.drawRect (20, 30, 130, 50);
sort.setLocation(0,220);
sort_label.setLocation(0,270);
sort_label.setSize(400,30);
}
public void actionPerformed(ActionEvent e) {
Sorting.selectionSort(random);
Sorting.insertionSort (sort);
repaint();
}
}
这是我的排序类
import java.awt.event.ActionEvent;
public class Sorting{
public static void selectionSort (Comparable[] list) {
int min;
Comparable temp;
for (int index = 0; index < list.length-1; index++)
{
min = index;
for (int scan = index+1; scan < list.length; scan++)
if (list[scan].compareTo(list[min]) < 0)
min = scan;
temp = list[min];
list[min] = list[index];
list[index] = temp;
}
}
public static void insertionSort (Comparable[] sorter) {
for (int index = 1; index < sorter.length; index ++){
Comparable key = sorter[index];
int position = index;
while (position > 0 && key.compareTo(sorter[position-1]) < 0){
sorter [position] = sorter[position-1];
position--;
}
sorter[position] = key;
}
}
然后这是我可比较的课程,我需要一些帮助
public class width implements Comparable {
int[] random = new int[20];
int[] sorter = new int[20];
@Override
public int compareTo(Object o) {
int result = 0;
if(random[1] == sorter[1])
result = random.length;
return result;
}
答案 0 :(得分:3)
你的同类课程应该是你要分类的。在这种情况下,您生成一个int
的随机数组,因此您实际上不需要实现compareTo
,因为Integer
已经实现了compareTo
。如果你要排序的东西比整数更复杂,你会创建一个新的类width
。
例如,如果您的Applet有一堆圆圈,它将按大小排序,您可以使用以下内容:
public class Circle implements Comparable<Circle> {
private Point center;
private double radius;
public Circle(double radius, Point center) {
this.center = center;
this.radius = radius;
}
// Other drawing functionality
public int compareTo(Circle c) {
if (c.radius > radius) return -1;
if (c.radius == radius) return 0;
return 1;
}
}
你知道吗?我们的对象更复杂,所以我们需要教Java如何比较一个圆圈,因为它不知道。