Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Tokens in Java

Tags:

java

split

token

While doing a school project I've been running into the following problem: After feeding a line into the processCommand() method from the run() method (using the console as a sort of text editor), I find that for whatever reason the tokens aren't reading properly and so I run to the 'else' clause of the processCommand() method even when the command should be simple and accurate (i.e. typing h into the console puts out "Please enter a valid command."). I'm sure there's something wrong with how I'm splitting the line, but for the life of me I can't figure it out. Can anyone help me?

    @Override
public void run() {
    Scanner scanner = new Scanner(System.in);
    String line;

    try {
        do {
            System.out.print("vi: ");
            line = scanner.nextLine();
            if(line.length() > 0){
                processCommand(line);
            }
        } while (!quit);
    } catch (Exception ex) {
        System.out.println("An error occurred.");
    }

    scanner.close();
    System.out.println("Goodbye!");
}

@Override
public void processCommand(String line) {
    String[] tokens = line.split(" ");
    if(tokens[0] == "b") {
        insertBefore(line.substring(3));
    }
    if(tokens[0] == "i") {
        insertAfter(line.substring(3));
    }
    if(tokens[0] == "m") {
        moveUp(Integer.parseInt(line.substring(3)));
    }
    if(tokens[0] == "u") {
        moveDown(Integer.parseInt(line.substring(3)));
    }
    if(tokens[0] == "r") {
        remove(Integer.parseInt(line.substring(3)));
    }
    if(tokens[0] == "d") {
        remove(Integer.parseInt(line.substring(3)));
    }
    if(tokens[0] == "c") {
        clear();
    }
    if(tokens[0] == "s") {
        try {
            save(line.substring(3));
        } catch (IOException e) {
        }
    }
    if(tokens[0] == "l") {
        try{
            load(line.substring(3));
        } catch (IOException e) {

        }
    }
    if(tokens[0] == "h") {
        displayHelp();
    }
    if(tokens[0] == "x") {
        exit();
    }
    else {
        System.out.println("Please enter a valid command.");
        return;
    }
}
like image 279
Akodobo Avatar asked Feb 04 '26 22:02

Akodobo


1 Answers

You shouldn't be using "==" for string comparison. Use the following:

if(tokens[0].equals("h"))...

Hope that helps!

like image 131
awolfe91 Avatar answered Feb 06 '26 12:02

awolfe91