Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package HTMLTAGS;
- import java.io.IOException;
- import java.util.Scanner;
- import java.util.Set;
- import java.util.HashSet;
- import java.util.Stack;
- import htmlSupport.*;
- public class HTML4 {
- private static Set<String> optionalTags = new HashSet<String>();
- private static void populateOptionalTags() {
- String [ ] optionals = {"p", "li", "html", "body", "tr", "td"};
- for (int i=0; i<optionals.length; i++)
- optionalTags.add(optionals[i]);
- }
- private static boolean isOptional(CSC300HTMLTag tag) {
- return optionalTags.contains(tag.getName());
- }
- public static void main(String[] args) throws IOException {
- Stack<CSC300HTMLTag> startTags = new Stack<CSC300HTMLTag>();
- Scanner console = new Scanner(System.in);
- CSC300HTMLTag nextTag, poppedTag;
- populateOptionalTags();
- System.out.println("Enter a URL");
- String url = console.next();
- HTMLTokenizer tokenizer = new HTMLTokenizer(url);
- while (tokenizer.hasNext()) {
- nextTag = tokenizer.next();
- if (nextTag.getType() == CSC300HTMLTag.START) {
- startTags.push(nextTag);
- //System.out.println("Tag Pushed");
- // push the name of the tag onto the stack
- }
- else if (nextTag.getType() == CSC300HTMLTag.SIMPLE){
- //System.out.println("SIMPLE");
- continue;
- }
- else {
- if(startTags.peek().getName().equals(nextTag.getName())){
- poppedTag = startTags.pop();
- //System.out.println("Valid so far");
- }
- else if(optionalTags.contains(startTags.peek().getName())){
- while(optionalTags.contains(startTags.peek().getName())){
- //System.out.println("HTML CODE IS VALID/BALANCED STUCK HERE");
- startTags.pop();
- //Was getting an empty stack exception so used the line below to fix that.
- if (startTags.isEmpty()){
- System.out.println("Code is Valid");
- return;
- }
- }
- }
- else {
- System.out.println("HTML CODE IS NOT VALID 1");
- return;
- }
- if (startTags.isEmpty()){
- System.out.println("HTML CODE IS NOT VALID 2");return;}
- // if the tag names of nextTag and poppedTag are the same,
- // continue
- // otherwise, if poppedTag doesn't require an end tag,
- // keep popping the stack until:
- //
- // (1) you find a matching tag (then HTML is valid so far)
- // (2) hasNext returns false (then HTML is not valid)
- // (3) the stack becomes empty (then HTML is not valid)
- }
- }
- System.out.println("HTML CODE IS VALID");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement