[英]Emulate a java sorting shell on the eclipse command prompt
我编写了一个程序,试图使用Eclipse创建“排序外壳”。 我可以做的一些基本功能是加载要使用的排序算法,卸载,使用算法进行排序以及使用特定ID从外壳中卸载算法。
对于所有排序算法(气泡,插入,快速等),我都有单独的类,但是我不知道如何将它们加载到外壳中。 这是我到目前为止的内容:
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;
}
任何帮助将非常感激!
我假设您知道如何编写代码来创建和填充数组,以及如何打印结果,所以在这里我不会打扰。
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.