我做了一些与我的项目有关的编码。我需要简单地将一个字符串值赋给从文件中读取的String数组。
但我无法理解为什么值始终为null。 string的值不会分配给数组。有人能解释我所犯的错误。
我在这里发布了我的代码。
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]);
始终打印为空。
答案 0 :(得分: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
}
如果在递增copying_strings
后打印变量r++
,显然会null
,因为没有传递任何内容。
答案 1 :(得分:0)
null
的数组值。所以请在打印字符串值后递增变量(r),如下所述,
while ((line = bufferReader.readLine()) != null) {
copying_strings[r] = line;
System.out.println("lll " + copying_strings[r++]);
System.out.println("lll " +line);
}