如何使用bufferedreader读取我的文本文件并将其插入Java堆栈中

时间:2013-02-18 20:34:16

标签: java bufferedreader stack

继承我的代码我是新的堆栈,不知道如何实现它们,特别是使用缓冲读卡器。我不知道如何实现编程的新代码堆栈代码。我必须编写一个程序,它将反转从我的txt文件读取的方向并打印出来。

try
{
    BufferedReader in = new BufferedReader(new FileReader("GoingThere.txt"));
    String line = in.readLine();
    while(line != null)
    {
           line.replace("West","East");
           line.replace("East","West");
           line.replace("North", "South");
           line.replace("South", "North");      
           line = in.readLine();
    }
}
catch(FileNotFoundException e)
{ 
  System.out.println("File Not Found"); 
}
catch(IOException e)
{ 
  System.out.println("IO Exception Found.");
}

2 个答案:

答案 0 :(得分:0)

你的问题让我深感困惑。但是,根据您的代码和文本文件的名称,我认为我可以推断您正在尝试做的事情。我猜你有一个学校作业,它给你一个A - >的方向列表。 B.您需要使用堆栈反转这些方向以给出B - > A.根据该假设,尝试:

Stack st = new Stack();
while (line != null) {
    st.push(line);
    line = in.readLine();
}

然后,您可以使用st.pop()以相反的顺序从堆栈中恢复您的行。

答案 1 :(得分:0)

The Same of your Codes but I Added The Stack  Hope you Understand it 
The implementation of stack :
Stack <String> stack = new Stack<String>();
stack.push(String);
stack.pop();

here is the  Same Example :

       Stack <String> stack = new Stack<String>();

    try
        {
        BufferedReader in = new BufferedReader(new FileReader("GoingThere.txt"));
        String line = in.readLine();
        String a,b,c,d;
        while(line != null)
        {
        System.out.println(a=line.replace("West","East"));
        System.out.println(b=line.replace("East","West"));
        System.out.println(c=line.replace("North", "South"));
        System.out.println(d=line.replace("South", "North"));

        stack.push(a);
        stack.push(b);
        stack.push(c);
        stack.push(d);    
        System.out.println("----------------- Stack Pushed -----------------");
        line = in.readLine();
        }
        System.out.println("Pop is Begin :");

        while(!stack.isEmpty()){

            System.out.println(stack.pop());
        }
        }

        catch(FileNotFoundException e)
        { 
          System.out.println("File Not Found"); 
        }
        catch(IOException e)
        { 
          System.out.println("IO Exception Found.");
        }