0

I am trying to separate each word in a string and then add them to a stack. Here is the code I wrote to do this. Every time I run the tester, it always returns an empty stack, but shouldn't the stack have <body> in it?

import java.util.Stack;

public class HTML3{
//main method
public static boolean checkBalance(String str) {
    Stack<String> stack = new Stack<String>();
    String[] words = str.split(" ");
    for (int i = 0; i < words.length; i++) {
        String tag = words[i];
        if(tag=="<body>" || tag=="<hl>" || tag=="<center>" || tag=="<p>" || tag=="<ol>" || tag=="<li>") {     
                stack.push(tag);
        }
    }

    return stack.isEmpty();
}

public static void main(String[]args)
{
    checkBalance("<body> <li>");
   }

}

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
Austin C.
  • 1
  • 1

1 Answers1

-2

You're close but == doesn't compare the Strings, it compares the objects in which case tag is a different object from "< body>" for example.

Use .equals() to compare Strings and it will work.

tag.equals("<body>")

If you learn to use the debugger or an IDE that provides code hints you can figure these things out on your own.

CmosBattery
  • 934
  • 7
  • 13
  • or equalsIgnoreCase() is good too if you don't care about case sensitivity, which is probably the case here. –  Nov 27 '17 at 00:36