Как я могу пройтись по дереву поиска и распечатать 5 лучших строк - PullRequest
0 голосов
/ 18 октября 2019

У меня есть программа, которая печатает количество строк, символов, целых чисел и идентификаторов из файла. Я также должен вывести из файла первые 5 встречающихся строковых символов, целых чисел и идентификаторов, но у меня возникают проблемы при обходе дерева поиска и при этом.

Я пытался отправить все в массив, но я получаю ошибки исключения

Вот мой код:

import java.io.*;

public class WordTree
{
public static void main(String[] args) throws IOException
{


    WordTree wordtree = new WordTree();
    WordTree numtree = new WordTree();
    WordTree idtree = new WordTree();
    WordTree chartree = new WordTree();
    TreeNode[] a = null;

    Scanner file = new Scanner(new File("words.txt"));

    String words[] = null;
    int lineNum = 0;
    int wordcount = 0;
    int numcount = 0;
    int idcount = 0; 
    int linecount = 0; 
    int charcount = 0;
    int i = 0;
    List<String> w = new ArrayList<String>();




    while(file.hasNextLine())
    {

        Scanner chopper = new Scanner(file.nextLine());

        lineNum++;

        linecount++;   

        while(chopper.hasNext())
            {
                    String next = chopper.next().replaceAll("\\p{Punct}","");
                    boolean numeric = true;

                    charcount += next.length();

                    try {
                        Double num = Double.parseDouble(next);
                    } catch (NumberFormatException e) {
                        numeric = false;
                    }

                    if (!numeric){
                        if (isValidID(next, next.length())){
                            idcount++;
                            idtree.add(next.toLowerCase(), lineNum);
                        }

                        wordtree.add(next.toLowerCase(), lineNum);
                        wordcount++;

                    }
                    else{
                        numtree.add(next.toLowerCase(), lineNum);
                        numcount++;
                    }


            }

    }


    System.out.println("Total number of words in the file: " + wordcount);
    System.out.println("Totoal number of integers in the file: " + numcount);
    System.out.println("Total number of identifiers in the file: " + idcount);
    System.out.println("The total number of lines in the file is: " + linecount);
    System.out.println("The total number of characters in the file is: " + charcount);


    System.out.println("******************* WORDS IN FILE ***************");
    wordtree.traverse();
    System.out.println("*******************INTEGERS IN FILE ***************");
    numtree.traverse();
    System.out.println("******************* IDENTIFIERS IN FILE ***************");
    idtree.traverse();







}

    private static TreeNode minimumElement(TreeNode right) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

String[] array;
int i = 0;
class TreeNode
{
    private TreeNode left, right;
    private String word;
    private TreeSet<Integer> lines;


    private int i = 0;
    private List<String> array = new ArrayList<String>();



    public TreeNode(String word)
    {
        this.word = word;
        lines = new TreeSet<Integer>();

    }

    @Override
    public String toString()
    {

        String output = "";

        output += word + " ";

        int count = 0;

        for(int i : lines)
        {

            count ++;
            output += i + " ";

        }
        array.add(count + " " + word);
        System.out.println(array);

        return output + "Total occurrences: " + count;

        }
    }

    private TreeNode root;

    public WordTree()
    {

    }

    public void add(String word, int line)
    {

            if(root == null)
            {
                root = new TreeNode(word);
                root.lines.add(line);
            }
            else
            {
                TreeNode curr = root;

                while(curr != null)
                {
                    if(word.equals(curr.word))
                    {
                        curr.lines.add(line);
                        break;
                    }
                    else if(word.compareTo(curr.word) < 0)
                    {
                        if(curr.left != null)
                        {
                            curr = curr.left;
                        }
                        else
                        {
                            curr.left = new TreeNode(word);
                            curr.left.lines.add(line);
                            break;
                        }
                    }
                    else
                    {
                        if(curr.right != null)
                        {
                            curr = curr.right;
                        }
                        else
                        {
                            curr.right = new TreeNode(word);
                            curr.right.lines.add(line);
                            break;
                        }
                    }
                }
            }

    }
    public void addNull()
    {
            if(root != null)
            {
                root = null;
            }

//void clearTree(treenode *node) {
//    if (node != NULL) {
//        clearTree( node->leftChild );
//        clearTree( node->rightChild );
//        delete( node ); // Or in Java, node = null;
    }

    public void traverse()
    {
        traverse(root);
        inOrder(root,array, 0);
    }


    public void inOrder(TreeNode node,String[] array, int i){

    if(node == null){  // recursion anchor: when the node is null an empty leaf was reached (doesn't matter if it is left or right, just end the method call
       return;
    }
    inOrder(node.left, array, i);   // first do every left child tree
    array[i++]= node.word;   // then write the data in the array
    inOrder(node.right,array,  i);  // do the same with the right child
    }

    public void traverse(TreeNode root)
    {
        if(root == null)
        {
            return;
        }

        traverse(root.left);
        System.out.println(root);
        traverse(root.right);
    }


    static boolean isValidID(String str, int n) 
        { 

            // If first character is invalid 
            if (!((str.charAt(0) >= 'a' && str.charAt(0) <= 'z') 
                || (str.charAt(0)>= 'A' && str.charAt(0) <= 'Z') 
                || str.charAt(0) == '_')) 

                    return false; 

            // Traverse the string for the rest of the characters 
                for (int i = 1; i < n; i++) 
                { 
                    if (!((str.charAt(i) >= 'a' && str.charAt(i) <= 'z') 
                        || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') 
                        || (str.charAt(i) >= '0' && str.charAt(i) <= '9') 
                        || str.charAt(i) == '_')) 
                        return false; 
                } 

                // String is a valid identifier 
            return true; 

        } 
    static boolean isValidWord(String str, int n) 
        { 

            // If first character is invalid 
            if (!((str.charAt(0) >= 'a' && str.charAt(0) <= 'z') 
                || (str.charAt(0)>= 'A' && str.charAt(0) <= 'Z')))

                    return false; 

            // Traverse the string for the rest of the characters 
            for (int i = 0; i < n; i++)  {  
            if (!((str.charAt(i) >= 'a' && str.charAt(i) <= 'z') 
                || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') 
                ))

                return false; 

            }
                // String is a valid identifier 
            return true; 

        } 
//    public static boolean checkWord(String word) {
//        // System.out.println(word);
//        try {
//            BufferedReader in = new BufferedReader(new FileReader(
//                "/usr/share/dict/web2"));
//            String str;
//            while ((str = in.readLine()) != null) {
//                if (str.indexOf(word) != -1) {
//                    return true;
//                }
//            }
//            in.close();
//        } catch (IOException e) {
//        }
//
//        return false;
//    }

}
...