-2

这是我的代码,我对堆栈很陌生,不知道如何实现它们,尤其是使用缓冲阅读器。我不知道如何实现编程新手的堆栈代码。我必须编写一个程序来反转从我的 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.");
}
4

2 回答 2

0

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

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

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

于 2013-02-18T20:54:38.053 回答
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.");
        }
于 2013-02-18T21:14:20.847 回答