在eclipse命令提示符上模拟java排序shell



我制作了一个程序,我试图使用eclipse制作一个'排序shell'。我可以做的一些基本功能是加载要使用的排序算法,卸载它,使用算法进行排序,并使用特定的ID从shell中卸载算法。

我对所有排序算法(Bubble, insert, 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;
}

任何帮助将非常感激!

我假设您知道如何编写代码来创建和填充数组,以及如何打印结果,因此在这里我就不再赘述了。

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;
    }
  }
}

最新更新