2016-09-16 125 views
1

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

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

这里我发布了我的代码。

Test.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()); 
     } 
    } 
} 

可有人请让我知道为什么

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

版画始终是一个空值。

+2

的r ++;'。你在阅读和打印之间增加'r',结果你在下一行打印什么,但是你还没有分配它,所以你总是有一个'空'。删除'r ++'并将打印改为'copies_strings [r ++]',你应该打印当前行,同时也增加'r'。 – SomeJavaGuy

回答

0

您的while-loop有错误。正确的顺序是首先读取一行,将它传递给String,打印并最终增加循环变量。

while ((line = bufferReader.readLine()) != null) {  // read a line 
    copying_strings[r] = line;       // pass to String 
    System.out.println("lll " + copying_strings[r]); // print for the 1st time 
    System.out.println("lll " + line);     // print for the 2nd time 
    r++;            // increment the looped variable 
} 

如果递增r++后打印变量copying_strings,你会得到明显null因为什么都在它获得通过。

0
  • 在打印字符串值之前,增加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);            
}