【问题标题】:Read an file of int with blank lines and save to a array - JAVA读取带空行的 int 文件并保存到数组 - JAVA
【发布时间】: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 对不起,我现在就做!

标签: java arrays file


【解决方案1】:
public class Stack {

    protected final int MAX = 1_000_000;
    protected int[] pilha;
    private int numero;
    
    Stack(){
        pilha = new int[MAX];
    }
    
    void add(int newElement){
        pilha[numero] = newElement;
        ++numero;
    }

    public int size() {
        return numero;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        boolean needsComma = false;
        for (int i = 0; i < numero; ++i) {
            if (needsComma) {
                sb.append(", ");
            }
            sb.append(pilha[i]);
            needsComma = true;
        };
        sb.append(']');
        return sb.toString(); // Arrays.toString(pilha);
    }
}

public static void main(String[] args) throws Exception {
    Stack guardar = new Stack();
    Path file = Paths.get("D:\\entradas\\tarefas1000.txt");
    Files.lines(file) //This method needs a parameter to work on
    .forEach(line -> {
        if (!line.trim().isEmpty()) {
            guardar.add(Integer.parseInt(line));
        }
    });
    System.out.println(guardar);
}

【讨论】:

  • 实际上Paths.get() 的优点是您不需要对分隔符进行硬编码。你可以写:Paths.get("D:", "entradas", "tarefas1000.txt")
  • @Abra 谢谢。 Path 是一个比File(磁盘驱动器文件)更新的类,它是一个泛化(还有类路径资源文件、zip 内的文件等)。 Files 类提供了许多可以用 Path 做的好东西,比如将文件读入字符串,以及读取所有行。
猜你喜欢
  • 2012-11-06
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多