Проверка HTML в Java, используется со связанным списком с использованием обобщений. Компилируется, но не завершается - PullRequest
0 голосов
/ 07 ноября 2018

Я разрабатываю это упражнение для моего предмета Структуры данных.

Мне нужно создать средство сопоставления тегов html, которое проверяет, правильно ли размещены теги, с помощью стека String. Стек должен быть одним связанным списком.

Код компилируется, но затем переходит в бесконечный цикл и печатает адрес памяти элементов списка вместо самих элементов.

Я размещаю файлы с кодом ниже:

--- LinkedList.java ---

public class LinkedList<T>
 {
   private Node<T> head; 
   private Node<T> tail;
   private int sizeCounter;
   private String listName;

public LinkedList()
{
    head = tail = null;
    sizeCounter = 0;
    listName = "list";
}

public LinkedList(String name)
{
    head = tail = null;
    sizeCounter = 0;
    this.listName = name;
}


public boolean isEmpty()
{
    if (sizeCounter == 0)
        return true;

    return false;
}

public int size()
{
    return this.sizeCounter;
}

public T scanNode(Node<T> node)
{
    return node.getItem();      
}

public T scanHead()
{
    return this.scanNode(head);
}

public T scanBack()
{
    return this.scanNode(tail);
}

public void insertAtFront(T item)
{
    Node<T> node = new Node<T>(item);

    if (isEmpty())
    {
        head = tail = node;
        sizeCounter = 1;
    } 

    else 
    {   node.setNext(head);
        head = node;
        ++sizeCounter;
    }

}

public void insertAtBack(T item)
{
    Node<T> node = new Node<T>(item);

    if (isEmpty())
    {
        head = tail = node; 
        sizeCounter = 1; 
    } 

    else 
    {
        tail.setNext(node); 
        tail = node;
        ++sizeCounter;
    }
 }


public T removeFromFront() throws EmptyListException
{
    if (isEmpty())
        throw new EmptyListException(listName);

    T removedItem = head.getItem();

    if (head==tail){
        head = tail = null;
        sizeCounter=0;}
    else 
    {
        Node<T> tmp = head.getNext();
        head = tmp; 
        --sizeCounter;
    }

    return removedItem;
}

public T removeFromBack() throws EmptyListException
{
    if (isEmpty())
        throw new EmptyListException(listName);

    T removedItem = tail.getItem();

    if (head==tail)
        {
        head = tail = null;
        sizeCounter=0;}
    else 
    {
        Node<T> tmp = head; 
        while (tmp.getNext()!=tail)
            tmp = tmp.getNext();

        tail = tmp;
        tmp.setNext(null);
        --sizeCounter;
    }

    return removedItem;
}


public void print() 
{   
    if (isEmpty()) 
    {
        System.out.print("This "+this.listName+" is Empty!!");

    }                                                       // end if

    System.out.print("The "+this.listName+" is ");
    Node<T> current = head;

                                                            // while not at end of list, output current node's data
    while (current != null) 
    {
        current.toString();
        current = current.getNext();
    }                                                       // end while



}
}

--- TagMatching.java ---

import java.io.*;

public class TagMatching {

public static void main(String[] args) throws IOException 
{
  if (args.length!=1)
  {
    System.err.println("Wrong set of arguments.Please input ONLY ONE path to html document");  
    System.exit(1);
  }
  else 
  {     
      StringStackImpl stack = new StringStackImpl();
      String filePath = args[0];

      if(!filePath.endsWith(".html"))
        {   
          System.err.println("Wrong type of file. Run the programme again!");
          System.exit(1);
        }
      else {

          FileReader htmlFile = null;
          try 
          {
            htmlFile = new FileReader(filePath);
          }

          catch (FileNotFoundException e) 
          {
            e.printStackTrace();
          }


          int inByte=0; 
          char inChar = ' ';
          do 
          {
            inByte= htmlFile.read();
            inChar = (char)inByte; 
            if (inChar == '<')
                    {
                      StringBuilder token = new StringBuilder('<');
                        do
                        {
                            inByte = htmlFile.read();
                            inChar = (char)inByte;
                            token.append(inChar);
                            inByte = htmlFile.read();
                        } while (inChar !='>');

                        String item = new String (token.toString());

                        if( !item.startsWith("</") )
                        {

                            stack.push(item.substring(1,item.length()-2));
                        }

                        else 
                        {
                            String example = stack.peek();
                                if (example == item.substring(2,item.length()-2))
                                    stack.pop();

                        }

                        stack.printStack(System.out);

                    }

          } while (inByte!=-1);

          htmlFile.close();

          if (stack.isEmpty())
              System.out.println("\n\nThe html file is ok and matching!\nThanks for using the programme!");
          else 
              System.out.println("The html file is not matched. Sorry!\nThanks for using the programme");


        }

  }}}

--- Node.java

    public class Node<T> {

    private T item;  // Item value of a node..made of generics
    private Node<T> next;  // Reference to next node

    public Node(T item)  //constructor with only the item as input
    {
        this.item = item;
        this.next = null; 
    }

    public Node(T data, Node<T> nextNode) //full constructor
    {
        this.item = data;           
        this.next = nextNode; 
    }

    public T getItem ()     //retrieve the item in node
    {
        return this.item; 
    }

    public void setItem(T item)
    {this.item = item;}

    public Node<T> getNext()    //retrieve the next Node
    {
        return this.next;
    }

    public void setNext(Node<T> next)
    {
        this.next = next;
    }

    public void toString(T item)
    {
         System.out.printf("%s\n",item);
    }

}

--- StringStack.java

import java.io.PrintStream;
import java.util.NoSuchElementException;

 /** Defines the methods for a Stack that handles String items
*/

public interface StringStack {


    /**
 * @return true if the stack is empty
 */

public boolean isEmpty();

/**
 * insert a String item to the stack
 */
public void push(String item);

/**
 * remove and return the item on the top of the stack
 * @return the item on the top of the stack
 * @throws a NoSuchElementException if the stack is empty
 */
public String pop() throws NoSuchElementException;

    /**
 * return without removing the item on the top of the stack
 * @return the item on the top of the stack
 * @throws a NoSuchElementException if the stack is empty
 */
public String peek() throws NoSuchElementException;

/**
 * print the elements of the stack, starting from the item
     * on the top,
 * to the stream given as argument. For example, 
 * to print to the standard output you need to pass System.out as
 * an argument. E.g., 
 * printStack(System.out); 
 */
public void printStack(PrintStream stream);

- StringStackImpl.java

import java.io.PrintStream;
import java.util.NoSuchElementException;


 public class StringStackImpl implements StringStack {

    private LinkedList<String> stringStack;

   public StringStackImpl()
{
    this.stringStack = new LinkedList<String>("Stack");
}


public boolean isEmpty() 
{
    if (stringStack.isEmpty())
        return true;
    else
        return false;
}


public void push(String item)  //einai stoiba ara opos mpainei etsi kai 8a bgei to stoixeio ara 8a xrisimopoihsoume atFront methodous
{
    stringStack.insertAtFront(item);

}


public String pop() throws NoSuchElementException {
    if (isEmpty()) throw new NoSuchElementException("ERROR!!! The stack is empty!!! ");
    else 
        return stringStack.removeFromFront();

}


public String peek() throws NoSuchElementException 
{
    if (isEmpty()) throw new NoSuchElementException("ERROR!!! The stack is empty!!! ");
    else 
        return stringStack.scanHead();
}


public void printStack(PrintStream stream) 
{
    stringStack.print();

}



public int size() {
    if (stringStack.isEmpty())
        return 0;
    else 
        return stringStack.size();
    }

}

Заранее спасибо за советы!

...