首页 > 解决方案 > 数组在写入后不保留其值

问题描述

我正在尝试将文件读入数组,每一行都将存储在数组的索引中。给定 text.txt 文件中的以下输入:

6afe
5af
3eafe
7fae
3sfs
1eef

我读入了数组,然后在控制台中打印出数组进行检查,但不知何故,数组在循环后没有保留它的值。我得到的输出是空的,之前和之后,但不在循环中间。请告诉我为什么 ?谢谢这是我得到的输出

nullline 0
nullline four
6afe
5af
3eafe
7fae
3sfs
1eef
nullline three
nullline four

我期望得到的输出是:

nullline 0             // array still empty here, i get it
    nullline four     // array still empty
    6afe         
    5af
    3eafe
    7fae
    3sfs
    1eef
    7fae      // where here are null three ? in the actual ouput
    3sfs      // null three ?

这是我的代码:

import java.io.*;

public class readSortWrite
{
    public static void main(String[] args) throws java.io.IOException
    {
        //input file
        // to count lineNum
        FileReader fr = new FileReader("text.txt");
        BufferedReader br = new BufferedReader(fr);
        //to read into array names[]
        FileReader fr1 = new FileReader("text.txt");
        BufferedReader br1 = new BufferedReader(fr1);

        // output file
        FileWriter fw = new FileWriter("sorted.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);

        // counting number of line
        int lineNum = 0;
        String line;
        line = br.readLine();
        while(line != null)
        {
            lineNum++;
            line = br.readLine();            
        }
        pw.close();
       // System.out.println(lineNum + "lines");  

        // create an array of of lineNum size and write each line of file into array
        String[] names = new String[lineNum];
        String str;
        str = br1.readLine();

        System.out.println(names[0]+ " line 0");
        System.out.println(names[4] + " line four");

        for (int i = 0 ; i<lineNum; i++)
        {
            while (str!= null)
            {
                names[i] = str;
                str = br1.readLine();
                System.out.println(names[i]);


            }             
        }
       // fr1.close();
        System.out.println(names[3]+ " line three");
        System.out.println(names[4] + " line four");



    }
}

标签: javaarrays

解决方案


前两行是null因为您创建数组并在初始化它们之前打印值04索引,就像这样

String[] names = new String[lineNum];
String str;
str = br1.readLine();

System.out.println(names[0]+ " line 0");
System.out.println(names[4] + " line four");

对于倒数第二行,while循环将读取buffer直到它为空但没有任何循环迭代for,因此仅填充names[0]

for (int i = 0 ; i<lineNum; i++)
{
  while (str!= null)
  {
    names[i] = str;
    str = br1.readLine();
    System.out.println(names[i]); 
  }             
}

将其更改为类似

int i =0;
while (str!= null && i < lineNum) {
  names[i] = str;
  str = br1.readLine();
  System.out.println(names[i]);
}  

推荐阅读