java - 将字符串的值分配给字符串数组

标签 java arrays string

我正在做一些与我的项目相关的编码。我需要简单地将一个字符串值分配给从文件中读取的字符串数组。

但我不明白为什么该值始终为空。字符串的值不会分配给数组。有人可以解释一下我所犯的错误吗?

这里我发布了我的代码。

测试.java

public class Test {

    public static void main(String[] args) throws IOException {
        //Tuning Jaccard Coefficient algorithm for Training set
        ReadFile_2 rf = new ReadFile_2();         
        rf.readFile("C:/Users/user/Desktop/Msc-2016/InformationRetrieval/project material/train.txt","Training");
    }
}

ReadFile_2.java

class ReadFile_2 {

    List<String> copying_strings1 = new ArrayList<>();
    String[] Apparted_Strings = new String[3];
    String[] copying_strings = new String[50];
    int arryListSize = copying_strings.length;
    static int value_of_shingle;
    static int best_Shingle;
    String[] fileType;
    int fileType_size;

    public void readFile(String fileName, String file_type) throws FileNotFoundException, IOException {

        //Name of the file
        try {
            if (file_type.equals("Training")) {
                best_Shingle = 2;
            } else if (file_type.equals("Testing")) {
                best_Shingle = value_of_shingle;
            }

            FileReader inputFile = new FileReader(fileName);
            BufferedReader bufferReader = new BufferedReader(inputFile);
            String line;
            int r = 0;

            while ((line = bufferReader.readLine()) != null) {
                copying_strings[r] = line;
                r++;
                System.out.println("lll " + copying_strings[r]);
                System.out.println("lll " +line);
                //Apparted_Strings = sp.apart_Strings_3(line);
                //CallingAlgo_4 c_a = new CallingAlgo_4(Apparted_Strings[0], Apparted_Strings[1], Apparted_Strings[2], best_Shingle, "Jaccard");
            }

            //Close the buffer reader
            bufferReader.close();
        } catch (Exception e) {
            System.out.println("Error while reading file line by line:" + e.getMessage());
        }
    }
}

有人可以告诉我为什么它的值(value)

System.out.println("lll " + copying_strings[r]);

始终打印为 null。

最佳答案

  • 在打印字符串值之前递增 while 循环变量 (r)。
  • 因此它会打印下一个数组值 null

因此,请在打印字符串值后增加变量 (r),如下所述,

while ((line = bufferReader.readLine()) != null) {
    copying_strings[r] = line;                        
    System.out.println("lll " + copying_strings[r++]);
    System.out.println("lll " +line);                                              
}

关于java - 将字符串的值分配给字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39529669/

相关文章:

java - 为什么我们在 Java 中使用自动装箱和拆箱?

c - C 中动态的、大小不可预测的数组

java - 同时向 HashMap 添加元素

java - 将一串十进制数字转换为 BCD 的算法

javascript - 在 JavaScript 中将数组作为函数参数传递

string - 在字符串中交换字符的最低成本,因此没有 3 个相同的字符是连续的

java - 在列上使用别名的查询会出错

java - java代码设置日期和时间的问题

java - java中对数组进行升序排序

jquery - 光滑的网格将分页中的所有行分组