我想从文本文件中读取内容,然后将其设置为car class中的某些变量。但它一直向我显示“java.lang.NullPointerException”。我不知道它有什么问题。有人能告诉我该怎么做吗?
错误行为cars[0].setRegion(tokens[2]);
这是文本文件。
CarInLot KLM456 ND Meter4 120
CarInLot VMK123 ME移动0
CarInLotDKC003 WA Meter5 30
Meter1无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();
}
}
这是汽车类。
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;
}
}
答案 0 :(得分:5)
所以你有这个代码
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]));
}
...
cars
已初始化,但其中的元素并非如此。您需要先对其进行初始化,否则它们为null
,您将获得NullPointerException
。
cars[someIndex] = new Car(...);
此外,您现在拥有代码的方式,您将始终覆盖数组中相同的Car
引用,即。索引为0的那个。您可能希望使用递增索引来初始化每个元素。