views:

61

answers:

2

here is what i have so far. the problem i am faceing is how do i find the number of elemets in the file so i can initialze the queue. Your suggestions will b most appritated.

class FileHandler {
BufferedReader data;
DataInputStream in;

    public FileHandler(String fileName) {
    try {
        data = new BufferedReader(new FileReader(fileName));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public FiFo fileToLines() {

///////////////////here is where i need ur help  whats teh string size////////////////////

    private FiFo lines=new FiFo(data.)
        String line = "";
    try {
        while ((line = data.readLine()) != null) {
            lines.add(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }*/
    return lines;
}

public void closeFile() {
    try {
        data.close();

    }

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

public class FiFo {

     private int index;
     private String[] queue;

     public FiFo(int size)
{
          queue=new String[size];
         index=0;

}

public void add(String element)
{
    queue[index]=element;
    index++;
}
public void remove()
{
    int temp=0;
    while(temp!=index)
    {
        queue[temp]=queue[temp+1];
        temp++;
    }
    index--;
}

public String get()
{
    return queue[0];
}

public int size()
{
    return index;
}

public void printQueue()
{
    for (int i=0;i<=index;i++)
        System.out.println(queue[i]);
}
A: 

Why do you want to implement your Fifo class ? Is it homework ?

Why wouldn't you use this class :

public Queue fileToLines() {

    LinkedList<String> lines = new LinkedList<String>();


    String line = "";
    try {
        while ((line = data.readLine()) != null) {
            lines.add(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }*/
    return lines;
}

With this one, you don't have to know the number of lines in the file.

Il you really want to have the count of lines in a file, see this topic.

Laurent K
its homework i have to implement a queue
Shaz
In that case, you could implement a queue for which it's not necessary to know the initial size. Initialize your queue with a size of (let's say) 100, then each time you add an item, check if the size is big enough. If not, add more size to your Array. (create a new storage array, and use java.util.Arrays.copy to copy the old into the new)
Laurent K
A: 

You have no way of understanding how many lines are in a file when you open it. One thing you can do is to is add all lines to a List, Your FiFo can take that list as its constructor param and use it as its backing data.

akf
thanks can suggest thats its better to amke the String Array in FiFo private or make it public cuz i also have to compare 2 quese and find teh common elements
Shaz