I have for two days tried to get my program to work, this is indeed a homework-assignment and a think my algorithm should be right, using a stack to check if the tags are balanced. I would be grateful if someone knows what is wrong with the code. This is what it looks like now:
public class HtmlParser {
private Stack<String> tagstack; // stack to collect only "<" characters.
public HtmlParser() {
tagstack = new Stack<String>();
}
private void processClosedTag(Scanner in) {
tagstack.pop();
in.next();
}
private void processOpenTag(Scanner in) {
tagstack.push(in.next()); // "<"
}
public boolean isCorrectlyNested(Scanner in) {
boolean isBalanced = false;
while(in.hasNext()) {
if(in.hasNext("<"))
processOpenTag(in); //and recurse until "/>"
else if(in.hasNext(">"))
processClosedTag(in);
}
if(tagstack.isEmpty())
isBalanced = true;
return isBalanced;
}//isCorrectlyNested
}//class
When I use the scanner object “in” and call for the methods in this class nothing happens in the console it only reads the what I write but then nothing happens it doesn’t even return my statements I have written like:
if(parser.isCorrectlyNested(input))
System.out.println("Correctly Nested!");
else
System.out.println("Need to nest properly");
This is of course in the main method where i use the HtmlParser instance “parser”.
You never actually move the scanner’s position if the next item is neither a less-than or greater-than symbol. Consider if the next character was an alpha-numeric string of some kind. Your while loop never returns because it never actually moves past the string if it isn’t what it is looking for, so your method never returns and your output never gets executed.