-4
我想從文本文件中讀取內容,然後將其設置爲car class中的一些變量。但它不斷向我顯示「java.lang.NullPointerException」。我不知道它有什麼問題。有人能告訴我該怎麼辦?不斷顯示:「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;
}
}
該文件是否也有這些空行,或者是您爲該問題添加的內容? –
顯示您正在接收的確切錯誤語句及其指向的行 – Prateek
使用堆棧跟蹤發佈完整錯誤。 –