문제

I am trying to simulate a terminal/file system. Right now I am working on parsing and tokenizing the commands.

I am trying to determine what is considered a valid command. My strategy is to check if index 2 element in my input array is anything other than the string "empty". If it is, my checkValidCommand method will return false.

I am currently getting this error when I run the program and enter in input as "hi":

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at fileSystem2.MainActivity.checkValidCommand(MainActivity.java:43)
    at fileSystem2.MainActivity.main(MainActivity.java:66)

I believe this problem is caused by having my String[] input having only 3 elements.

code:

check valid input.

    private static boolean checkValidCommand(String[] commandTokens) {
        //boolean valid = false;
        if (commandTokens[0].equals("exit")) {
            return true;
        }
        else if (!commandTokens[2].equals("empty")) {
            return false;
        }
        return true;
    }

Code that parses commands

String[] input = new String[3];

        for (int i = 0; i < input.length; i++) {
            input[i] = "empty";
        }

        while(!input[0].equals("exit")) {
            Scanner sc = new Scanner(System.in);
            input = sc.nextLine().split(" ");
            if (checkValidCommand(input)) {
                System.out.print("Invalid Command!");
                continue;
            }
            System.out.println(input.length);
            switch(input[0]) {
                // vi
                case "vi":
                    System.out.println("hi");
                    break;
                // ls
                case "ls":
                    break;
                // mkdir
                case "mkdir":
                    break;
                // pwd  
                case "pwd":
                    break;
            }   
        }
도움이 되었습니까?

해결책

The command

input = sc.nextLine().split(" ");

does not fill the existing array (referenced by input) with data.

It creates a new array and assigns a reference to it to input.

Whatever input was pointing to becomes dereferenced and a subject to garbage collection.

다른 팁

I'm not sure how to get the length of the array in Java (I will assume that it is array.length() for this answer so forgive me if I got it wrong) but basically you're accessing the 2nd element without ensuring that sc.nextLine().split(" "); will actually return 3 elements for you...

So I would recommend changing:

if (checkValidCommand(input)) {

To

if (input.length() > 2 && checkValidCommand(input)) {
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top