【发布时间】:2020-10-07 15:34:38
【问题描述】:
我试图读取一个 txt 文件并保存到一个数组中,但我的数组输出中只得到了 null。我错过了什么?
txt 文件的一部分,是的,数字之间有这些空行
306741
581016
783580
529978
772824
54939
797499
235178
675900
365768
561760
986962
242452
621124
555822
80045
914383
634731
18956
创建数组的代码
public class Stack {
protected final int MAX=1000000;
protected Integer[]pilha;
Stack(){
pilha = new Integer[MAX];
}
void add(Integer newElement){
int i;
for(i=0;pilha[i]!=null;i++);
pilha[i]= newElement;
}
还有主要的:
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("D:\\entradas\\tarefas1000.txt");
Scanner sc = new Scanner(file);
Stack guardar=new Stack();
while (sc.hasNext()){
guardar.add(sc.nextInt());
}
sc.close();
System.out.println(Arrays.toString(guardar.pilha));
}
}
【问题讨论】:
-
for(i=0;pilha[i]!=null;i++);末尾有一个分号,所以重复;- 空语句。 -
@JoopEggen 它应该这样做。目的是找到下一个可用的数组索引。
-
调试您的应用程序。确保正在读取文件,并且实际调用了
Stack::add。 -
我复制了这个以在我的本地系统中运行。它工作正常。你能显示你得到的实际输出吗?
-
@Abra 对不起,我现在就做!