Question

Hi,

So I have a finished class for the most part aside of the toFile method that takes a file absolute path +file name and writes to that file. I'd like to write everything that is in my run method also the toFile method. (They are the last two methods in the class). When I write to the file this is what I get.

Empty Set- Returns True if empty False if not Result of empty set before inserting: true --Inserting Names-- IsEmpty result after inserting: false -Level Order Iterator-- [?Empty Set--, Returns True ?f empty False ?f not, Result of empty set before inserting: true, --Inserting Names--][--Empty Set-, Returns True if empty Fal ot, Result of empty set before inserting: true,Inserting Names--1 -Sorted Order Iterator-- --Empty Set Inserting Names-Result of empty set before inserting: true Returns True ?f empty False if not Valera is not an employee of the company! Joseph is not an employee of the company! Jack is not an employee of the company! Rick James is not an employee of the company! ?Size Function- Size is: 4 --Erasing Boogie-- Size is: 4 --Level Order Iterator after removal- [?Empty Set--, Returns True if empty False if not, Result of empty set before inserting: true,-Inserting Names--][--Empty Set-, Returns True if empty Fal ot, Result of empty set before inserting: true, --Inserting Names--] ?Sorted Order iterator after removal- --Empty SetInserting Names- Result of empty set before inserting: true Returns True if empty False if not The max is: Valera The nin is: --Empty Set--Instead of the desired

That I get to my counsel. I am having trouble writing my Iterator functions to the file as well as some of my methods.

Here is my source code. I only need help with the ToFile method. I'd like for it to look like the console print out.

Thanks

import java.util.LinkedList;

import java.util.Queue;

import java.util.List;

import java.util.ArrayList;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.PrintStream;

public class lab4Strashko {

   private static Node root = null;

  

   //constructor

   private static class Node {

       public String key;

       public Node left, right;

      

       public Node(String key) {

           this.key = key;

       }

   }

   // returns 1 is empty 0 if not

   public static boolean isEmpty() {

       return root == null;

   }

  

   public static void makeEmpty(){

       root = null;

   }

   public static String findMax(){

       return MaxHelp(root);

   }

   public static String max="";

  

   public static String MaxHelp(Node x){

       if (x == null){

           return("Empty");

       }if (x.left==null && x.right ==null){

           return x.key;

           }

       if (max.compareTo(x.key)<0){

               max = x.key;

               MaxHelp(x.left);

               MaxHelp(x.right);  

       }

       return max;

   }

   public static String findMin(){

       return MinHelp(root);

   }

  

   public static String MinHelp(Node x){

       if (x == null){

           return("Empty");

       }if (x.left==null && x.right ==null){

           return x.key;

           }

       if (min.compareTo(x.key)>0){

               min = x.key;

               MinHelp(x.left);

               MinHelp(x.right);  

       }

       return min;

   }

   // the number of nodes in the tree

   public static int size() {

       return size(root);

   }

   public static String min="zzzzzzz";

   public static int size(Node x) {

       if (x == null)

           return 0;

       int sz = 1;

       sz += size(x.left);

       sz += size(x.right);

       return sz;

   }

   //returns if name parameter is an employee of the company

   public static void find(String name) {

       if (findhelp(root, name)) {

           System.out.printf("%s is an employee.", name);

       } else {

           System.out.printf("%s is not an employee of the company!", name);

       }

   }

   public static boolean findhelp(Node x, String name) {

       if (x == null)

           return false;

       String s = x.key;

       if (s.equals(name)) {

           return true;

       }

       else {

           return findhelp(x.left, name) || findhelp(x.right, name);

       }

   }

   public static void erase(String key)

{

root = erase(root, key);

}

public static Node erase(Node root, String key)

{

if (root == null) return root;

if ((key.compareTo(root.key) < 0))

root.left = erase(root.left, key);

else if ((key.compareTo(root.key) > 0))

root.right = erase(root.right, key);

else

{

if (root.left == null)

return root.right;

else if (root.right == null)

return root.left;

  

root.key = minValue(root.right);

root.right = erase(root.right, root.key);

}

return root;

}

  

public static String minValue(Node root)

{

String minv = root.key;

while (root.left != null)

{

minv = root.left.key;

root = root.left;

}

return minv;

}

  

   //Inserts employee into tree

   public static void put(String key) {

   root = put(root, key);

      }

      static Node put(Node root, String key) {

      if (root == null) {

      root = new Node(key);

      return root;

      }

      if ((key.compareTo(root.key) < 0)){

      root.left = put(root.left, key);

      }else if ((key.compareTo(root.key) > 0))

      root.right = put(root.right, key);

      return root;

      }

   // Test for equality

   public static boolean areEquals(lab4Strashko a, lab4Strashko b) {

       return areEquals(lab4Strashko.root, lab4Strashko.root);

   }

   private static boolean areEquals(Node x, Node y) {

       if (x == null) {

           return (y == null);

       } else {

           return (y != null) && x.key == y.key && areEquals(x.left, y.left) && areEquals(x.right, y.right);

       }

   }

   public static Iterable<String> levelOrder() {

       Queue<String> keys = new LinkedList<>();

       Queue<Node> queue = new LinkedList<>();

       queue.add(root);

       while (!queue.isEmpty()) {

           Node n = queue.remove();

           if (n == null)

               continue;

           keys.add(n.key);

           queue.add(n.left);

           queue.add(n.right);

       }

       System.out.print(keys);

       return keys;

   }

      public static void SortedOrder()

      {

   SortedOrder(root);

      }

  

      // Sorted traversal of BST

      public static void SortedOrder(Node root)

      {

      if (root != null)

      {

      SortedOrder(root.left);

      System.out.print(root.key + " ");

      SortedOrder(root.right);

      }

      }

   //File reader taking file input

   public static List<String> fileReader(String file){

       List<String> list = new ArrayList<String>();

       try(BufferedReader in = new BufferedReader(new FileReader(file))){

           String str;

           while((str = in.readLine()) != null){

               list.add(str);

           }

           return list;

   }catch(IOException e){

       e.printStackTrace();

       return list;

   }

   }

   //main runs run method with input file

   //Insert files absolute path

   //File reader reads names line by line

   public static void main(String[] args) {

       //My location of Input file

       //Run function prints to console

       run("/Users/vboogie/Downloads/DataStructures/workspace/Lab4Strashko/src/Input.txt");

       //toFile function prints to output file

       //makes tree empty for second run

       //You can choose your own location

       toFile("/Users/vboogie/Downloads/DataStructures/workspace/Lab4Strashko/src/Output.txt");

   }

   // Prints test to console

   private static void run(String file) {

       System.out.print("--Empty Set--");

       System.out.println();

       System.out.print("Returns True if empty False if not");

       System.out.println();

       System.out.printf("Result of empty set before inserting: %b", isEmpty());

       System.out.println();

       System.out.print("--Inserting Names--");

       System.out.println();

       List<String> Names = fileReader(file);

       for (String Name: Names){

           put(Name);

       }

       System.out.println();

       System.out.printf("IsEmpty result after inserting: %b", isEmpty());

       System.out.println();

       System.out.print("--Level Order Iterator--");

       System.out.println();

       levelOrder();

       System.out.println();

       System.out.print("--Sorted Order Iterator--");

       System.out.println();

       SortedOrder();

       System.out.println();

       find("Valera");

       System.out.println();

       find("Joseph");

       System.out.println();

       find("Jack");

       System.out.println();

       find("Rick James");

       System.out.println();

       System.out.print("--Size Function--");

       System.out.println();

       System.out.printf("Size is: %d",size());

       System.out.println();

       System.out.print("--Erasing Boogie--");

       erase("Boogie");

       System.out.println();

       System.out.printf("Size is: %d",size());      

       System.out.println();

       System.out.print("--Level Order Iterator after removal--");

       System.out.println();

       levelOrder();

       System.out.println();

       System.out.print("--Sorted Order Iterator after removal--");

       System.out.println();

       SortedOrder();

       System.out.println();

       System.out.printf("The max is: %s",findMax());

       System.out.println();

       System.out.printf("The min is: %s",findMin());

       System.out.println();

      

              

   }

   //Prints Test to File

   public static void toFile(String file){

       makeEmpty();

       try{

      PrintStream o = new PrintStream(new File(file));

      PrintStream console = System.out;

      System.setOut(o);  

      System.out.print("--Empty Set--");

           System.out.println();

           System.out.print("Returns True if empty False if not");

           System.out.println();

           System.out.printf("Result of empty set before inserting: %b", isEmpty());

           System.out.println();

           System.out.print("--Inserting Names--");

          

           List<String> Names = fileReader(file);

           for (String Name: Names){

               put(Name);

           }

           System.out.println();

           System.out.printf("IsEmpty result after inserting: %b", isEmpty());

           System.out.println();

           System.out.print("--Level Order Iterator--");

           System.out.println();

           System.out.printf("%s",levelOrder());

           System.out.println();

           System.out.print("--Sorted Order Iterator--");

           System.out.println();

           SortedOrder();

           System.out.println();

           find("Valera");

           System.out.println();

           find("Joseph");

           System.out.println();

           find("Jack");

           System.out.println();

           find("Rick James");

           System.out.println();

           System.out.print("--Size Function--");

           System.out.println();

           System.out.printf("Size is: %d",size());

           System.out.println();

           System.out.print("--Erasing Boogie--");

           erase("Boogie");

           System.out.println();

           System.out.printf("Size is: %d",size());

           System.out.println();

           System.out.print("--Level Order Iterator after removal--");

           System.out.println();

           System.out.print(levelOrder());

           System.out.println();

           System.out.print("--Sorted Order Iterator after removal--");

           System.out.println();

           SortedOrder();

           System.out.println();

           System.out.printf("The max is: %s",findMax());

           System.out.println();

           System.out.printf("The min is: %s",findMin());

           System.out.println();

      }catch(FileNotFoundException e){

               e.printStackTrace();

       }finally{

       }

       }

   }

0 0
Add a comment Improve this question Transcribed image text
Answer #1

https://www94.zippyshare.com/v/MAMbQyKE/file.html

Just download this input.txt replace with your input.txt over this path

/Users/vboogie/Downloads/DataStructures/workspace/Lab4Strashko/src

and then run

here is my code

import java.util.LinkedList;

import java.util.Queue;

import java.util.List;

import java.util.ArrayList;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.io.PrintStream;

public class lab4Strashko {

    private static Node root = null;

  

    //constructor

    private static class Node {

        public String key;

        public Node left, right;

      

        public Node(String key) {

            this.key = key;

        }

    }

    // returns 1 is empty 0 if not

    public static boolean isEmpty() {

        return root == null;

    }

  

    public static void makeEmpty(){

        root = null;

    }

    public static String findMax(){

        return MaxHelp(root);

    }

    public static String max="";

  

    public static String MaxHelp(Node x){

        if (x == null){

            return("Empty");

        }if (x.left==null && x.right ==null){

            return x.key;

            }

        if (max.compareTo(x.key)<0){

                max = x.key;

                MaxHelp(x.left);

                MaxHelp(x.right);  

        }

        return max;

    }

    public static String findMin(){

        return MinHelp(root);

    }

  

    public static String MinHelp(Node x){

        if (x == null){

            return("Empty");

        }if (x.left==null && x.right ==null){

            return x.key;

            }

        if (min.compareTo(x.key)>0){

                min = x.key;

                MinHelp(x.left);

                MinHelp(x.right);  

        }

        return min;

    }

    // the number of nodes in the tree

    public static int size() {

        return size(root);

    }

    public static String min="zzzzzzz";

    public static int size(Node x) {

        if (x == null)

            return 0;

        int sz = 1;

        sz += size(x.left);

        sz += size(x.right);

        return sz;

    }

    //returns if name parameter is an employee of the company

    public static void find(String name) {

        if (findhelp(root, name)) {

            System.out.printf("%s is an employee.", name);

        } else {

            System.out.printf("%s is not an employee of the company!", name);

        }

    }

    public static boolean findhelp(Node x, String name) {

        if (x == null)

            return false;

        String s = x.key;

        if (s.equals(name)) {

            return true;

        }

        else {

            return findhelp(x.left, name) || findhelp(x.right, name);

        }

    }

    public static void erase(String key)

    {

        root = erase(root, key);

    }

    public static Node erase(Node root, String key)

    {

        if (root == null) return root;

        if ((key.compareTo(root.key) < 0))

            root.left = erase(root.left, key);

        else if ((key.compareTo(root.key) > 0))

            root.right = erase(root.right, key);

        else

        {

            if (root.left == null)

                return root.right;

            else if (root.right == null)

                return root.left;

          

            root.key = minValue(root.right);

            root.right = erase(root.right, root.key);

        }

        return root;

    }

  

    public static String minValue(Node root)

    {

        String minv = root.key;

        while (root.left != null)

        {

            minv = root.left.key;

            root = root.left;

        }

        return minv;

    }

  

    //Inserts employee into tree

     public static void put(String key) {

           root = put(root, key);

        }

        static Node put(Node root, String key) {

            if (root == null) {

                root = new Node(key);

                return root;

            }

            if ((key.compareTo(root.key) < 0)){

                root.left = put(root.left, key);

            }else if ((key.compareTo(root.key) > 0))

                root.right = put(root.right, key);

            return root;

        }

    // Test for equality

    public static boolean areEquals(lab4Strashko a, lab4Strashko b) {

        return areEquals(lab4Strashko.root, lab4Strashko.root);

    }

    private static boolean areEquals(Node x, Node y) {

        if (x == null) {

            return (y == null);

        } else {

            return (y != null) && x.key == y.key && areEquals(x.left, y.left) && areEquals(x.right, y.right);

        }

    }

    public static Iterable<String> levelOrder() {

        Queue<String> keys = new LinkedList<>();

        Queue<Node> queue = new LinkedList<>();

        queue.add(root);

        while (!queue.isEmpty()) {

            Node n = queue.remove();

            if (n == null)

                continue;

            keys.add(n.key);

            queue.add(n.left);

            queue.add(n.right);

        }

        System.out.print(keys);

        return keys;

    }

      public static void SortedOrder()

        {

           SortedOrder(root);

        }

  

        // Sorted traversal of BST

        public static void SortedOrder(Node root)

        {

            if (root != null)

            {

                SortedOrder(root.left);

                System.out.print(root.key + " ");

                SortedOrder(root.right);

            }

        }

    //File reader taking file input

    public static List<String> fileReader(String file){

        List<String> list = new ArrayList<String>();

        try(BufferedReader in = new BufferedReader(new FileReader(file))){

            String str;

            while((str = in.readLine()) != null){

                list.add(str);

            }

            return list;

    }catch(IOException e){

        e.printStackTrace();

        return list;

    }

    }

    //main runs run method with input file

    //Insert files absolute path

    //File reader reads names line by line

    public static void main(String[] args) {

        //My location of Input file

        //Run function prints to console

        //run("Input.txt");
       run("/Users/vboogie/Downloads/DataStructures/workspace/Lab4Strashko/src/Input.txt");

        //toFile function prints to output file

        //makes tree empty for second run

        //You can choose your own location
        //toFile("Output.txt");
        toFile("/Users/vboogie/Downloads/DataStructures/workspace/Lab4Strashko/src/Output.txt");

    }

    // Prints test to console

    private static void run(String file) {

        System.out.print("--Empty Set--");

        System.out.println();

        System.out.print("Returns True if empty False if not");

        System.out.println();

        System.out.printf("Result of empty set before inserting: %b", isEmpty());

        System.out.println();

        System.out.print("--Inserting Names--");

        System.out.println();

        List<String> Names = fileReader(file);

        for (String Name: Names){

            put(Name);

        }

        System.out.println();

        System.out.printf("IsEmpty result after inserting: %b", isEmpty());

        System.out.println();

        System.out.print("--Level Order Iterator--");

        System.out.println();

        levelOrder();

        System.out.println();

        System.out.print("--Sorted Order Iterator--");

        System.out.println();

        SortedOrder();

        System.out.println();

        find("Valera");

        System.out.println();

        find("Joseph");

        System.out.println();

        find("Jack");

        System.out.println();

        find("Rick James");

        System.out.println();

        System.out.print("--Size Function--");

        System.out.println();

        System.out.printf("Size is: %d",size());

        System.out.println();

        System.out.print("--Erasing Boogie--");

        erase("Boogie");

        System.out.println();

        System.out.printf("Size is: %d",size());      

        System.out.println();

        System.out.print("--Level Order Iterator after removal--");

        System.out.println();

        levelOrder();

        System.out.println();

        System.out.print("--Sorted Order Iterator after removal--");

        System.out.println();

        SortedOrder();

        System.out.println();

        System.out.printf("The max is: %s",findMax());

        System.out.println();

        System.out.printf("The min is: %s",findMin());

        System.out.println();

      

              

    }

    //Prints Test to File

     public static void toFile(String file){

         makeEmpty();

         try{

            PrintStream o = new PrintStream(new File(file));

            PrintStream console = System.out;

            System.setOut(o);  

            System.out.print("--Empty Set--");

            System.out.println();

            System.out.print("Returns True if empty False if not");

            System.out.println();

            System.out.printf("Result of empty set before inserting: %b", isEmpty());

            System.out.println();

            System.out.print("--Inserting Names--");

          

            List<String> Names = fileReader(file);

            for (String Name: Names){

                put(Name);

            }

            System.out.println();

            System.out.printf("IsEmpty result after inserting: %b", isEmpty());

            System.out.println();

            System.out.print("--Level Order Iterator--");

            System.out.println();

            System.out.printf("%s",levelOrder());

            System.out.println();

            System.out.print("--Sorted Order Iterator--");

            System.out.println();

            SortedOrder();

            System.out.println();

            find("Valera");

            System.out.println();

            find("Joseph");

            System.out.println();

            find("Jack");

            System.out.println();

            find("Rick James");

            System.out.println();

            System.out.print("--Size Function--");

            System.out.println();

            System.out.printf("Size is: %d",size());

            System.out.println();

            System.out.print("--Erasing Boogie--");

            erase("Boogie");

            System.out.println();

            System.out.printf("Size is: %d",size());

            System.out.println();

            System.out.print("--Level Order Iterator after removal--");

            System.out.println();

            System.out.print(levelOrder());

            System.out.println();

            System.out.print("--Sorted Order Iterator after removal--");

            System.out.println();

            SortedOrder();

            System.out.println();

            System.out.printf("The max is: %s",findMax());

            System.out.println();

            System.out.printf("The min is: %s",findMin());

            System.out.println();

        }catch(FileNotFoundException e){

                e.printStackTrace();

         }finally{

         }

         }

     }

Let me know if you have any doubt , please thumbs up for me :)

Add a comment
Know the answer?
Add Answer to:
Hi, So I have a finished class for the most part aside of the toFile method...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can you take a look at my code that why the maxDepth function is not working?...

    Can you take a look at my code that why the maxDepth function is not working? public class BinaryTree {          class Node{        int key;        Node left,right;               public Node(int item) {            key = item;            left = right = null;        }    }       Node root;       public void BinaryTree(){        root = null;    }           void...

  • I have almost done with this code to Implement Huffman Coding. However I have an error...

    I have almost done with this code to Implement Huffman Coding. However I have an error at the "Heap<Tree>". Could anyone help with solving this issue, really appreciated. Thank you!! import java.util.Scanner; public class HuffmanEncoding { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a text: "); String text = input.nextLine();    int[] counts = getCharacterFrequency(text); // Count frequency System.out.printf("%-15s%-15s%-15s%-15s\n", "ASCII Code", "Character", "Frequency", "Code");    Tree tree = getHuffmanTree(counts); // Create a Huffman tree String[]...

  • Hello. I have written the following function to remove a value from a Binary Search Tree using re...

    Hello. I have written the following function to remove a value from a Binary Search Tree using resources my professors gave and stuff I found online. The problem is I don't know how it works and I need to know how it works to finish the rest of the project. public boolean remove(T value){ if(value == null) return false; class RemoveBSTObj{ private boolean found = false; private Node removeBST(Node root, T value){ if(root == null) return root; //IF there is...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • JAVA QUESTION: *******THE QUESTION:******** /** numberOfNodesAtDepth    *    * Returns the number of nodes with...

    JAVA QUESTION: *******THE QUESTION:******** /** numberOfNodesAtDepth    *    * Returns the number of nodes with depth == d    * Precondition: none    *    * param: d the depth to search for    *    * hint: use a recursive helper function    *        * ToDo 4    */    public int numNodesAtDepth(int d) {        return -1;    } **********USEFUL CODE FROM THE ASSIGNMENT:*********** public class simpleBST<Key extends Comparable<Key>, Value> {    private Node root;            ...

  • 1. Write a function in Tree class which returns true if and only if the tree...

    1. Write a function in Tree class which returns true if and only if the tree satisfies the binary search tree property. The function’s header line is public boolean isValidBST() And in the attached code, you just need to finish the function after the comment: “//Instructor hint: please write your code here:” Make sure you execute your code, and the result in the main function after calling your function should be same as the prompt message I write. Clearly you...

  • Return a method as an expression tree Hi guys. I need to return a method as...

    Return a method as an expression tree Hi guys. I need to return a method as an expression tree, it's currently returning null. public static ExpressionTree getExpressionTree(String expression) throws Exception {       char[] charArray = expression.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); return et; } In the above method, et needs to have a value. -- Take a look at the complete class below. Kindly assist. ; public class ExpressionTree extends BinaryTree { private static final String DELIMITERS...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • Preliminaries Download the template class and the driver file. Objective Learn how to traverse a binary...

    Preliminaries Download the template class and the driver file. Objective Learn how to traverse a binary search tree in order. Description For the template class BinarySearchTree, fill in the following methods: insert - Inserts values greater than the parent to the right, and values lesser than the parent to the left.parameters elem - The new element to be inserted into the tree. printInOrder - Prints the values stored in the tree in ascending order. Hint: Use a recursive method to...

  • Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate ins...

    Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate insert operation in binary search tree. Please fill in the missing part for the insert method to make the program work. The expected output should be as follows. 20 30 40 50 60 70 80 Part B: Find Lowest Common Ancestor (LCA) of a Binary Search Tree. According to WikiPedia definition , The lowest common ancestor is defined between two nodes v and...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT