无法成功获取索引

时间:2014-08-15 06:25:02

标签: java

这是我的代码:

import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import javax.swing.*;

class SyntaxErrorException extends Exception {
    public SyntaxErrorException() {
        super();
    }

    public SyntaxErrorException(String msg) {
        super(msg);
    }
}

public class CLI {

    private static int loc;
    private static boolean first = true;
    private static String terminalPrompt = "CLI>";
    private static String errorPrompt = "ERR>";
    private static String historyPrompt = "HIS>";
    private static Vector<String> fnName = new Vector<String>();
    private static Vector<String> fnDir = new Vector<String>();
    private static String[][] help = {
        {
            "alert", 
            "Creat a popup box.", 
            "alert <string>"
        },
        {
            "echo", 
            "Print text to console", 
            "echo <string>"
        },
        {
            "exit", 
            "Exit console", 
            "exit"
        },
        {
            "help", 
            "Get help message", 
            "help"
        },
        {
            "history", 
            "Print all input by user", 
            "history"
        },
        {
            "prompt",
            "Change the prompt before the line.",
            "prompt <selector> <content>"
        },
        {
            "start", 
            "Start an application", 
            "start <appname> [args]"
        },
        {
            "time", 
            "Print date and time to console", 
            "time"
        },
        {
            "wait", 
            "Wait for certein time", 
            "wait <int>"
        },
        {
            "write", 
            "Write to file", 
            "write ( to <string> write/content <string> | from <string> )"
        }
    };

    public static String strJoin(String[] aArr, String sSep) {
        StringBuilder sbStr = new StringBuilder();
        for (int i = 0, il = aArr.length; i < il; i++) {
            if (i > 0)
                sbStr.append(sSep);
            sbStr.append(aArr[i]);
        }
        return sbStr.toString();
    }

    private static String[] defaultArg;
    private static Vector<String> history = new Vector<String>();

    static void pushErr(String errPrompt, String errMsg) {
        System.out.println(errPrompt + " " + errMsg);
    }

    static void handleCommand(String command, String[] arg){
        switch(command.toLowerCase()){
            case "alert":
                StringJoiner sj = new StringJoiner(" ");
                for(String ele : arg){
                    sj.add(ele);
                }

                JOptionPane.showMessageDialog(null, sj.toString());
                break;
            case "echo":
                try {
                    for(String ele : arg){
                        System.out.print(ele + " ");
                    }
                } catch (Exception ex){}
                System.out.println();
                break;
            case "exit":
                System.exit(0);
                break;
            case "fn":
                try {
                    loc = Arrays.asList(arg).indexOf("fn/location");

                    if(arg[0] == ""){
                        break;
                    }

                    switch(arg[0]){
                        case "add":
                            if(loc <= 1) {
                                break;
                            }

                            if(arg.length < 4) {
                                break;
                            }

                            fnName.add(strJoin(Arrays.copyOfRange(arg, 1, loc), " "));
                            fnDir.add(strJoin(Arrays.copyOfRange(arg, loc + 1, arg.length), " "));

                            break;
                        case "list":
                            for(int i = 0; i < fnName.size(); i++) {
                                System.out.println("FUNCTION #" + Integer.toString(i));
                                System.out.println("Name: \"" + fnName.get(i) + "\"");
                                System.out.println("Dir:  \"" + fnDir.get(i) + "\"");
                            }
                            break;
                        case "run":
                            int pos = Arrays.asList(fnName).indexOf(strJoin(Arrays.copyOfRange(arg, 1, arg.length), " "));
                            String ln;

                            // Doesn't work
                            if(pos >= 0) {
                                BufferedReader br = new BufferedReader(new FileReader(fnDir.get(pos)));
                                while((ln = br.readLine()) != null) {
                                    System.out.println("Line ##");
                                    handleCommand(ln);
                                }
                            }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case "help":
                for(String[] ele : help) {
                    System.out.println("Command:     " + ele[0]);
                    System.out.println("Descryption: " + ele[1]);
                    System.out.println("Syntax:      " + ele[2]);
                    System.out.println();
                }
                break;
            case "history":
                for(String ele : history){
                    System.out.println(historyPrompt + " " + ele);
                }
                break;
            case "prompt":
                try {                   
                    if(arg[0] == ""){
                        break;
                    }

                    switch(arg[0]) {
                        case "command":
                            terminalPrompt = strJoin(Arrays.copyOfRange(arg, 1, arg.length), " ");
                            break;
                        case "error":
                            errorPrompt = strJoin(Arrays.copyOfRange(arg, 1, arg.length), " ");
                            break;
                        case "history":
                            historyPrompt = strJoin(Arrays.copyOfRange(arg, 1, arg.length), " ");
                            break;
                        default:
                            pushErr(errorPrompt, "Wrong selector.");
                            break;
                    }
                } catch (NullPointerException e) {
                    pushErr(errorPrompt, "No selector.");
                }

                break;
            case "start":
                try {
                    /* loc = Arrays.asList(arg).indexOf("start/arg");

                    if(loc < 1){
                        break;
                    }

                    String cmd = strJoin(Arrays.copyOfRange(arg, 0, loc), " ");
                    String cmdArg = strJoin(Arrays.copyOfRange(arg, loc + 1, arg.length), " ");

                    Process p = new ProcessBuilder(cmd, cmdArg).start(); */

                    if (!"cmd".equals(arg[0])) {
                        Runtime.getRuntime().exec(strJoin(arg, " "));
                    } else {
                        Runtime.getRuntime().exec("cmd /c start " + strJoin(arg, " "));
                    }
                } catch (IOException e) {
                    pushErr(errorPrompt, "IOException Occured.");
                }
                break;
            case "time":
                Calendar cal = Calendar.getInstance();
                cal.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                System.out.println( sdf.format(cal.getTime()) );
                break;
            case "wait":
                try {
                    Thread.sleep(Long.parseLong(arg[0]));
                } catch (NumberFormatException nfe) {
                    pushErr(errorPrompt, "Invalid Number!");
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                } catch (NullPointerException npe) {
                    pushErr(errorPrompt, "Wait time not defined.");
                } catch (IllegalArgumentException iae) {
                    pushErr(errorPrompt, "Invalid Number : Smaller than 0");
                }
                break;
            case "write":
                try {
                    loc = Arrays.asList(arg).indexOf("write/content");
                    String strln;

                    switch(arg[0]){
                        case "to":
                            if(loc < 1){
                                System.out.println("No write/content specified.");
                                break;
                            }

                            BufferedWriter bw = new BufferedWriter(new FileWriter(strJoin(Arrays.copyOfRange(arg, 1, loc), " ")));
                            String[] contentParts = Arrays.copyOfRange(arg, loc + 1, arg.length);
                            String content = strJoin(contentParts, " ");

                            bw.write(content);
                            bw.write("\n");
                            bw.close();

                            break;
                        case "from":
                            BufferedReader br = new BufferedReader(new FileReader(strJoin(Arrays.copyOfRange(arg, 1, arg.length), " ")));

                            while((strln = br.readLine()) != null){
                                System.out.println(strln);
                            }

                            br.close();
                            break;
                        default:
                            System.out.println("Write : case not defined.");
                    }
                } catch (FileNotFoundException ex) {
                    pushErr(errorPrompt, "File (Directory) not found, File name invalid or File writing failed.");
                } catch (NullPointerException ex) {
                    pushErr(errorPrompt, "NullPointerException occured.");
                } catch (Exception ex) {
                    pushErr(errorPrompt, "Unexpected Exception occured. Will terminate app in 2 seconds......");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // Do nothing
                    }
                    System.exit(1);
                }
                break;
            case "":
                break;
            default:
                System.out.println("Command '" + command + "' is not available.");
        }
    } 

    static void handleCommand(String command){
        handleCommand(command, defaultArg);
    }

    public static void main(String[] args){
        try {
            Scanner sc = new Scanner(System.in);
            String input;

            while(true){
                if(first == true){
                    first = false;
                }else{
                    System.out.println();
                }

                System.out.print(terminalPrompt + " ");
                /* Forever loop. Retrieve user input here, and handle it. */
                input = sc.nextLine();

                history.add(input);

                if(input.contains(" ")){
                    String[] parts = input.split(" ");
                    handleCommand(parts[0], Arrays.copyOfRange(parts, 1, parts.length));
                }else{
                    handleCommand(input);
                }
            }
        } catch (NoSuchElementException ex) {
            System.out.println();
            System.out.println("User Pressed CTRL + C : Application Exiting.");
            System.exit(0);
        }
    }
}

这是我的目录树:

| CLI.class
| CLI$1.class
| SyntaxErrorException.class
| command.cli

这是command.cli的内容:

echo This is a function

我在java CLI

时这样做了
fn add testFn fn/location command.cli
fn run testFn

我希望看到结果:

CLI> fn add testFn fn/location command.cli

CLI> fn run testFn
This is a function

我在JOptionPane.showMessageDialog(null, Integer.toString(pos));中尝试了case "run":,但我得到了-1

这一行有什么问题:

int pos = Arrays.asList(fnName).indexOf(strJoin(Arrays.copyOfRange(arg, 1, arg.length), " "));

任何帮助将不胜感激。

0 个答案:

没有答案