gpt4 book ai didi

java - 我的 get 方法不会显示 arraylist 值

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:25 24 4
gpt4 key购买 nike

我是 java 和 stackOverflow 的新手,所以如果我没有发布有关我的问题的所有必要信息,请耐心等待。基本上,我试图从 .txt 文件中读取行并将它们存储在堆栈中。我还需要在不同的类中访问这个堆栈。所以我创建了一个 get 方法,但它总是返回 null。请帮忙!

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;

public class Hints {

private Stack stack;
private File f;
private String line;
private Scanner scanner;

public Hints(){
f = new File("hints.txt");
stack = new Stack();
}

public void getList() throws FileNotFoundException, IOException {

scanner = new Scanner(f);

while(scanner.hasNextLine()) {
line = scanner.nextLine();
stack.add(line);
}
scanner.close();
}

public Stack getStack(){
return stack;
}

}

当我尝试使用简单的 System.out.print 打印堆栈时,它将显示为 null。我的问题在哪里?谢谢。

最佳答案

你的代码工作正常。我认为在调用 getStack() 方法之前您没有调用 getList() 方法。

try {
Hints hints = new Hints();
hints.getList(); // adds to the stack
Stack s = hints.getStack(); // return the stack
int stackSize = s.size();

for (int i = 0; i < stackSize; i++) {

System.out.println(s.pop()); // pop from the stack
}
} catch (IOException ex) {
Logger.getLogger(JavaApplication18.class.getName()).log(Level.SEVERE, null, ex);
}

在调用 getStack() 方法之前,必须先调用 getList() 方法。因为 getList() 方法添加从 txt 文件读取的值。然后只有您可以调用 getStack() 方法。否则堆栈中没有任何值。

关于java - 我的 get 方法不会显示 arraylist 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com