我想从文本文件中读取内容,然后将其设置为car class中的一些变量.但它一直向我显示"java.lang.NullPointerException".我不知道它有什么问题.有人能告诉我该怎么办?
错误行是 cars[0].setRegion(tokens[2]);
这是文本文件.
CarInLot KLM456 ND Meter4 120
CarInLot VMK123 ME移动0
CarInLotDKC003 WA Meter5 30
仪表1无10
CarInLot IML84U ND Meter6 800
这是测试类.
import java.util.Scanner;
import java.io.*;
public class test
{
public static void main(String[] args) throws IOException
{
// Get the filename.
String filename = "input.txt";
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
if(filecotent.startsWith("Meter")){
cars[0].setPlate(tokens[1]);
}
}
System.out.println(cars[0].toString());
// Close the file.
inputFile.close();
}
}
Run Code Online (Sandbox Code Playgroud)
这是汽车类.
public class Car {
private String plate;
private String region;
private int minutes;
public Car(String carPlate, String carRegion,
int carMinutes) {
plate = carPlate;
region = carRegion;
minutes = carMinutes;
}
public Car(Car object2) {
plate = object2.plate;
region = object2.region;
minutes = object2.minutes;
}
public void setPlate(String pl) {
plate = pl;
}
public void setRegion(String re) {
region = re;
}
public void setMinutes(int mi) {
minutes = mi;
}
public String getPlate() {
return plate;
}
public String getRegion() {
return region;
}
public int getMinutes() {
return minutes;
}
public String toString() {
String string = "Car's information: "
+ "\n"
+ "\nLicense Plate: " + plate
+ "\nLicense Plate Resgistration Region: " + region
+ "\nParked time" + minutes
+ "\n";
return string;
}
}
Run Code Online (Sandbox Code Playgroud)
所以你有这个代码
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
...
Run Code Online (Sandbox Code Playgroud)
cars已初始化,但其中的元素不是.你需要先将它们初始化,否则它们就是null你得到的NullPointerException.
cars[someIndex] = new Car(...);
Run Code Online (Sandbox Code Playgroud)
此外,您现在拥有代码的方式,您将始终覆盖Car数组中的相同引用,即.索引为0的那个.您可能希望使用递增索引来初始化每个元素.
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |