我制作了一个程序,我试图制作一个排序shell'使用eclipse。我可以做的一些基本功能是加载要使用的排序算法,卸载它,使用算法排序并使用特定ID从shell卸载算法。
我有所有排序算法(Bubble,Insertion,Quick等)的单独类,但我不知道如何将它们加载到shell中。这就是我到目前为止所做的:
public static void main(String[] args) {
boolean exit_loop = true;
while (exit_loop){
String[] command;
command = input();
switch(command[0]){
case "load":
// ???
}
break;
case "tag":
break;
case "sort":
break;
case "unload":
break;
case "quit":
exit_loop = false;
break;
default:
System.out.println("Input a valid command!");
break;
}
}
}
public static String[] input(){
Scanner user_input = new Scanner( System.in );
String command;
System.out.print("sort:>");
command = user_input.next();
String[] first = command.split("\\s+");
return first;
}
所以,即使我能够获得用户输入,我也不确定如何实际加载我的排序算法类(我将其作为单独的类实现)。
以下是我如何实施其中一种排序算法的示例:
class Bubble implements SortingAlgorithms{
public int[] sort(int[] array){
int temp;
boolean swap = true;
while(swap){
swap = false;
for (int i=0; i < array.length-1; i++){
if (array[i] > array[i + 1]){
temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swap = true;
}
}
}
return array;
}
private String id;
public String name() {
return id;
}
public void name(String name) {
id = name;
}
非常感谢任何帮助!
答案 0 :(得分:0)
我假设您知道如何编写代码来创建和填充数组,以及如何打印结果,这样我就不会在这里烦恼。
public static void main(String[] args) {
boolean exit_loop = false;
SortingAlgorithms selectedalgo = null;
int[] array = null;
while (!exit_loop) {
String[] command;
command = input();
switch (command[0]) {
case "load":
SortingAlgorithms newalgo = null;
String algoname = command[1]; // "Bubble" etc.
try {
Class c = Class.forName(algoname);
newalgo = c.newInstance();
}
catch (Exception e) {
}
if (newalgo == null) {
System.out.println("Unknown algorithm: " + algoname);
}
else {
selectedalgo = newalgo;
}
break;
case "sort":
if (selectedalgo == null) {
System.out.println("Load an algorithm first!");
}
else if (array == null) {
System.out.println("Provide an array first!");
}
else {
array = selectedalgo.sort(array);
}
break;
case "unload":
selectedalgo = null;
break;
case "quit":
exit_loop = true;
break;
default:
System.out.println("Input a valid command!");
break;
}
}
}