0 java nullpointerexception java-io
我的应用程序旨在将正好1500个项目的现有文本文件(一行一行)读入一个项目类对象数组中.目标是将数据放入数组中,这样我就可以将此应用程序用作转换存档以获取我正在编写的新程序的起点.
package sandboxPackage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class mainClass {
public static void main(String[]args) throws FileNotFoundException, IOException {
InputStream in = new FileInputStream(new File("C:\\Documents and Settings\\Adam\\Desktop\\Cloud Project\\MasterIndex.library"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
itemClass[] m = new itemClass[1500];
int i = 0;
while ((line = reader.readLine()) != null) {
m[i].index = line; // crash is here
m[i].location = reader.readLine();
m[i].item = reader.readLine();
m[i].description = reader.readLine();
i++;
}
//Print the entire list
for (i = 0; i == 1499; i++) {
System.out.println(m[i].index);
System.out.println(m[i].location);
System.out.println(m[i].item);
System.out.println(m[i].description);
//System.out.println("This is item #" + i + 1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是itemClass:
package sandboxPackage;
public class itemClass{
String index;
String item;
String description;
String location;
}
Run Code Online (Sandbox Code Playgroud)
文本文件如下所示:索引位置项目描述索引位置项目描述索引..
编译器声称NullPointerException在第20行,这是while循环的第一行,但我只是看不到它.我已经看了大约一千个同样错误的其他例子,但它仍然没有为我计算.
您只是声明一个对象数组:
itemClass[] m = new itemClass[1500];
Run Code Online (Sandbox Code Playgroud)
但是你永远不会在这个数组中实例化对象.因此,访问任何实例变量将抛出一个NullPointerException
在循环中添加数组对象的实例化:
while ((line = reader.readLine()) != null) {
m[i] = new itemClass();// change the constructor if u need to
m[i].index = line; // crash is here : should no more crash
m[i].location = reader.readLine();
m[i].item = reader.readLine();
m[i].description = reader.readLine();
i++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
198 次 |
| 最近记录: |