【问题标题】:Reading in textfile into Stack and print out elements in reverse order将文本文件读入堆栈并以相反的顺序打印出元素
【发布时间】:2020-08-18 06:17:40
【问题描述】:

我正在尝试读取文本文件(文本行),使用 push 方法将所有元素放入堆栈。一旦我这样做了,我计划使用 pop 方法逐行打印所有元素。

  • 一次读取一行输入,然后将这些行写入
  • 倒序,使最后输入的行先打印,然后
  • 倒数第二个输入行,以此类推。
class part1{

    //pushing element on the top of the stack 
    static void stack_push(Stack<String> stack){
        for(int i = 0; i< stack.length(); i++){
            stack.push(i);
        }
    }

    static void stack_pop(Stack<String> stack){
        System.out.println("Pop :");

        for(int i = 0; i < stack.length(); i++){
            String y = (String) stack.pop();
            System.out.println(y);
        }
    }

    public static void main(String args[]){
        BufferedReader br = new BufferedReader(new FileReader("randomFile.txt"));
        stack_push(br);
    }

}

【问题讨论】:

  • 您的代码无法编译。您将BufferedReader 的对象传递给stack_push,但此方法没有任何匹配参数。
  • 你的问题到底是什么?
  • 我很困惑我应该如何将每一行从文本文件推送到堆栈
  • @bobbyverm - 阅读一些基本教程,如 docs.oracle.com/javase/tutorial/essential/io/file.html 以了解如何从文件中读取行。阅读时在堆栈中添加一行。
  • 为什么将缓冲读取器作为 Stack 传递,为什么要推入这个堆栈整数?

标签: java data-structures stack


【解决方案1】:

读取文件并将其内容推入堆栈的迭代(“经典”)方法:

public static void main(String args[]) {
    String fileName = "randomFile.txt";

   // create a bufferedReader 
    try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {

        // create a stack (Note: do not use the Stack class here, it is inherited from Vector which is deprecated.)
        Deque<String> stack = new ArrayDeque<>();

        // read the file line by line and push the lines into the stack
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stack.push(line);
        }

        // pop the values from the stack and print them
        while (stack.peek() != null) {
            System.out.println(stack.pop());
        }

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

声明式(“现代”)方法:

public static void main(String args[]) {
    String fileName = "randomFile.txt";
    // create stream from the input file
    try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

        // create a stack (Note: do not use the Stack class here, it is inherited from Vector which is deprecated.)
        Deque<String> stack = new ArrayDeque<>();

        // push the lines from the stream into the stack
        stream.forEach(stack::push);

        // print the lines from the stack (Note: the stack is not modified here!)
        stack.stream().forEach(System.out::println);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    相关资源
    最近更新 更多