好吧我想出瞭如何製作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;
}
一個「寬度」對象是「小於」(或「大於」)又是什麼意思? –
我不知道你的意思 – blankwall
你有'類寬實現Comparable'這意味着你想比較兩個'寬'對象。所以如果你聲明瞭'width w1'和'width w2'。你如何決定'w1'是否在'w2'之前,反之亦然? –