它没有提供任何输出,但代码运行没有错误。我想显示所有方法,包括冒泡排序,选择排序和比较排序的结果?我该如何调用这些方法。当我运行它时,它不会给我任何输出。所以,我只需要帮助来运行代码。
public static void main(String[] args) {
int[] A = new int[100];
int[] B = new int[100];
}
//get a random number;
private int getRand() {
Random in = new Random();
return in.nextInt(100);
}
//fill an array with numbers from 0 to 99;
public static void fillArray(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
}
//copy an array to another;
public static void copyArray(int[] aArray, int[] bArray) {
for (int i = 0; i < aArray.length; i++) {
bArray[i] = aArray[i];
}
}
//swap two numbers in an array according to index;
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
//random select two numbers in an array and switch them;
int disorderArray(int[] array) {
int i, j;
i = getRand();
j = getRand();
swap(array, i, j);
//System.out.println("the index of the 2 swapped numbers are " + i + " " +
j
);
return i;
}
//print out the array;
public static void printArray(int[] array, int col) {
for (int i = 0; i < array.length - col + 1; i += col) {
for (int j = i; j < i + col; j++)
System.out.print("number " + j + " is " + array[j] + "; ");
System.out.println();
}
for (int i = array.length - array.length % col; i < array.length; i++)
System.out.print("number " + i + " is " + array[i] + "; ");
System.out.println();
System.out.println();
}
//bubble sort;
public void bubbleSort(int[] array) {
for (int i = array.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] > array[j + 1])
swap(array, j, j + 1);
}
}
}
//selection sort;
public void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int p = i;
for (int j = i + 1; j < array.length; j++)
if (array[p] > array[j])
p = j;
if (i != p)
swap(array, i, p);
}
}
//compare two arrays;
public static boolean compareArrays(int[] aArray, int[] bArray) {
boolean s = true;
int i = 0;
if (aArray.length == bArray.length) {
while (s && i < aArray.length) {
if (aArray[i] != bArray[i])
s = false;
i++;
}
}
return s;
}
}
答案 0 :(得分:1)
您已经实现了一些方法,但您需要使用main
方法调用它们,例如
public static void main(String[] args) {
int[] A = new int[100];
int[] B = new int[100];
fillArray(A);
// more method calls...
}
注意,您已实现了类(static
)方法和实例(非静态)方法。你如何称呼它们的语义不同。如果您的程序是在名为Foo
的类中实现的,则可以编写以下内容:
// method call to class method
Foo.fillArray();
// method call to instance metod requires an instance
Foo fooInstance = new Foo();
int randomNumber = fooInstance.getRand();
通常,您使用实例方法来操作实例变量和类方法来操作类变量,或者更常见的是作为不涉及状态的辅助方法。有关这方面的更多信息可以在Oracle Java教程的Understanding Class Members章节中找到(向下滚动到类方法)。