10001a
10001a

Reputation: 53

Using an AVL tree in java

I have the AVLNode and AVLTree classes, i have the methods to remove and insert nodes and i have a print method. I want to use these methods to create a AVL tree. On input i want to write "Add x" and "Remove x". I wrote this but when i print nothing shows

 public static void main(String[] args) throws IOException {
    int i;
    BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(scanner.readLine());
    String[] words = new String[n];
    AVLTree<Integer> t = new AVLTree<Integer>();

    for (i = 0; i < n; i++) {
        String splitn = scanner.readLine();
        words[i] = (splitn.split(" ")[0]);
        int M = Integer.parseInt(splitn.split(" ")[1]);
        if (words[i] == "Add") {
            t.insert(M);
        }
        if (words[i] == "Remove") {
            t.remove(M);
        }

    }
    t.print();

}

Upvotes: 0

Views: 540

Answers (1)

Octahedron
Octahedron

Reputation: 901

Change:

if (words[i] == "Add")

to:

if (words[i].equals("Add"))

And similarly for the "Remove" case. The equals method will compare the strings character by character, but the == operator just checks whether the two strings are the same object in memory. So, the reason nothing prints is that nothing is being added or removed in the first place!

Upvotes: 2

Related Questions