Hi everyone!
Im trying to fill up a tree with the entries from a text file and I can read the file and I know how to make a tree object. I just dont know how to combine these two to populate the tree.
Any ideas are appreciated!

Idea: Read the data from the files into a variable and insert it into the tree. After you try that, see if you can eliminate this variable and insert the data directly into the tree :)

Is this a tree like in a data structure, like a binary tree or a red/black tree, or are we talking about the Swing class JTree, or what are we talking about?

Is this a tree like in a data structure, like a binary tree or a red/black tree, or are we talking about the Swing class JTree, or what are we talking about?

it's a data structure

Okay. Now, where are you getting stuck. You say you can read the file, and you know how to make the tree object. So where's the trouble?

Okay. Now, where are you getting stuck. You say you can read the file, and you know how to make the tree object. So where's the trouble?

I dont know how to populate the tree with the entries in the file. I have two separate things going on - the reader file and a tree but I cant plug in what I read from the file in the tree.
Here is my reader file.Right now, Im saving the entries from my numbers.txt file into a string instead of a tree.

import java.io.*;

public class File {
    BufferedReader in;
    String read;
 
    public File(){
        try {
            //open a bufferedReader to file helloworld.txt
            in = new BufferedReader(new FileReader("numbers.txt"));

            //read a line from helloworld.txt and save into a string
            read = in.readLine();

            //print out the line
            System.out.println("file output: " + read);

            //safely close the BufferedReader after use
            in.close();
        }catch(IOException e){
            System.out.println("There was a problem:" + e);
        }
    }

    public static void main(String[] args){
        File File = new File();
    }
}

Okay, what you're doing now is

in = new BufferedReader(new FileReader("numbers.txt"));

create an input pipe for the file

read = in.readLine();

you read a line from the file and store it into a String

System.out.println("file output: " + read);

then you report back what you found

in.close();

and close the file.


So instead, you want to open the file, read all of the lines, and put them into some sort of data structure so you can play with them later.

Let's start with making one long String out of them. This will mean making a StringBuffer and looping on the read stage of this. What will you use for a loop control test? I suggest you look at the BufferedReader.readline() documentation if you're not sure. When you exit the loop, you'll use the StringBuffer.toString() method to convert it into a String.

Here is my new reader file. Now I have to make my tree object. Should I make the tree where my string currently is so when the file is being read the information from it goes directly to the tree?

import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    FileInputStream fstream = new FileInputStream("numbers.txt");
	 
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
  
    while ((strLine = br.readLine()) != null)   {
      
	System.out.println (strLine);
    }
    
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

It looks like this reads the file and prints it to the screen.

If you want to go ahead and try to insert the Strings into the tree at this stage, you can go ahead and give it a go - sounds like you have an idea of how you want to do it.

Im trying something here and it doesnt work at the moment but think Im on the right track. Id appreciate any feedback.

import java.util.Scanner;
import java.io.*;
import java.lang.Character;
import java.io.*;
import java.util.*;

public class BinaryTree {

    public static void main(String[] args)
    {
        new BinaryTree().run();
    }

    static class Node 

   {

        Node left;
        Node right;
        int value;
		  int occur;
		  int visited = 0;
        public Node(int value) {
            this.value = value;
        }
    }
 Node rootNode;
 String fname;
 int count;
 Stack treeStack = new Stack();
 Stack printStack = new Stack();
	public void getFileName() {
		Scanner in = new Scanner(System.in);
		System.out.println("Enter file name please.");
		fname = in.nextLine();
		System.out.println("You entered " + fname);
	}
	public void readFileContents() {
		boolean looping;
		DataInputStream in;
		String line;
		int j, len;
		char ch;
		stackOb myStack = new stackOb(20);

		try {
			in = new DataInputStream(new FileInputStream(fname));
			looping = true;
			int b = 0;
			while (looping) {
 				
				if (null == (line = in.readLine())) 
				{
					looping = false;
					in.close();
				}
				else
				{
				 int a = Integer.parseInt(line);
				 insert(rootNode, a);
					System.out.println(a);					
				 
				}
				
			}// end while
			System.out.println(b);
		}// end try
		
 
		catch(IOException e) {
			System.out.println("Error " + e);
		} //end catch

	 		
	}

    public void run()
	  {
     
       getFileName();
		 readFileContents();
        System.out.println("Traversing tree recursivly");
         		  printInOrder(rootNode);
	     System.out.println("Traversing tree iterativly");
       			  iterative(rootNode);
		  System.out.println(count + " number of comparrisons");
		  
			 printOut();

    }

    public void insert(Node node, int value) {
    		if(rootNode == null)
			{
			  rootNode = new Node(value);
			  count++; 
			} 
		   else if (value < node.value)
				{
            if (node.left != null) {
                insert(node.left, value);
					 count++;
	         } 
				else 
				{
                System.out.println("  Inserted " + value + 
                                " to left of node " + node.value);
                node.left = new Node(value);
            }
        } 
		  else if (value > node.value) {
            if (node.right != null) {
                insert(node.right, value);
					 count++;
            } 
				else {
                System.out.println("  Inserted " + value + " to right of node " + node.value);
                node.right = new Node(value);
            }
        }
		  else if (value == node.value){
		  	count++;
		  	node.occur = node.occur++;
			}  
  }


    public void printInOrder(Node node) {
   
		  if (node != null) {
            printInOrder(node.left);
			
            System.out.println("  Traversed " + node.value);
	
					 String print = Integer.toString(node.value); 
				 		treeStack.push(print);
				//		System.out.println("pushed " + print);					
 				
            printInOrder(node.right);
        	}
		
		
    }
public void iterative(Node root){
	 
   Stack nodes = new Stack();
   nodes.push(root);
   Node currentNode;
   while (! nodes.isEmpty()){
//	System.out.println("while loop");
      currentNode = (Node)nodes.peek();

      if (currentNode.left != null && currentNode.left.visited == 0){
         nodes.push(currentNode.left);
		//System.out.println("left");
			}
     
      else if (currentNode.right != null && currentNode.right.visited == 0){
	
			System.out.println(currentNode.value);
			currentNode.visited =1;
			nodes.pop();
		
			
         nodes.push(currentNode.right);      
			}
		else {
			System.out.println(currentNode.value);
			currentNode.visited = 1;
			nodes.pop();
			
			}
		
      System.out.println("Node data: "+currentNode.value);
   }
}
	 public void printOut(){
	 
	 while (! treeStack.isEmpty()){
	 printStack.push(treeStack.pop());
	 }
	 
	 try {
              FileWriter outFile = new FileWriter("write");
              PrintWriter out = new PrintWriter(outFile);
              
     		   while (! printStack.isEmpty()){
     			
  					String blah = (String)printStack.pop();
           	   out.println(blah);
  				System.out.println("trying to print " +blah);	
			}
			out.println(" Number of comparissons " + count);
              out.close();
          } catch (IOException e){
              e.printStackTrace();
          }
      }
}

nvm. this was an example program and I have gotten another one that works now. thanks all.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.