控制台抛出异常:java.lang.nullpointerexception当我尝试添加和打印数组变量的值时



我是一名新秀Java程序员。但是,我遇到了一个小错误,我似乎无法弄清楚。任何帮助将不胜感激。

在此程序中,我正在尝试读取文件并将文件数据存储在变量中,数组大小等于文件中的行数。

例如:如果文件中有10行,则变量的数组大小也应为10。存储它们后,我想显示它们。(我已经知道如何显示数据)。

但是我有一个java.lang.NullPointerException错误。

我认为我的代码中的错误在Athlete类的setVariable方法中存在,或者main中的readFile函数存在。

setVariable方法用于将从文件提取的数据设置为数组类型变量(名称,姓氏,ID号,公民身份,时间)。

readFile函数用于读取文件中的数据,将数据存储在临时变量中,然后将临时变量的值发送到setVariable作为参数。

该文件按以下顺序包含以下值:("名称姓氏iDnumber公民时间")

class Athlete
{
private
String[] firstName;
String[] lastName;
String[] citizen;
int[] id;
float[] time;
public
void Athlete(int s) //Setting the size of the array variables.
{
    firstName = new String[s];
    lastName = new String[s];
    citizen = new String[s];
    id = new int[s];
    time = new float[s];
}
void setVariables(String fName,String lName, int idNumber, String citizenship, float t, int lineNumber)
{
    firstName[lineNumber]=fName;
    lastName[lineNumber]=lName;
    id[lineNumber]=idNumber;
    citizen[lineNumber]=citizenship;
    time[lineNumber]=t;
    System.out.println(firstName[lineNumber]+"t"+lastName[lineNumber]+"t"+id[lineNumber]+"t"+citizen[lineNumber]+"t"+time[lineNumber]);
}
}
//Main CLASS
public class marathon {
static Scanner console;
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
    //STEP-1: FILE
    openFile(); //Step 1.1: Open the File
    System.exit(0);
}
static void openFile()
{
    try
    {
        console = new Scanner (new File("C:/Eclipse_Wokspace/Assignment-2/src/Marathon.txt"));
        //Step 1.2: Read the File
        readFile();
    }
    catch (Exception e)
    {
        System.out.println("File did not open because of "+e);
    }
}   static void readFile()
{
    int size=0;
    Athlete athlete = new Athlete();
    while (console.hasNext())
    {
        String a,b,d; int c; float e; //Read the data in the file and store them in temporary variables.
        a=console.next(); //First Name
        b=console.next(); //Last Name
        c=console.nextInt(); //ID-Number
        d=console.next(); //Citizenship
        e=console.nextFloat(); //Time
        //Step 1.3: Store File Data
        athlete.setVariables(a, b, c, d, e, size);
        size++;
    }
    athlete.Athlete(size);
}
}

马拉松TXT文件错误

我不能将图像嵌入本文中的原因不允许我在此帖子上上传任何图像。

您的 Athlete构造函数期望大小参数。但是,您第一次创建运动员不使用任何争论,因此,此默认为Java的"默认构造函数",该构造器除了将Super称为Super,基本上是。

因此,您需要使用构造函数,该构造函数实际上分配了您很快就会填充的那些阵列。问题是,编写代码的方式,直到阅读整个文件并尝试修改Athlete

之后,您才知道大小。

您可以采用多种方法,我可以为此文件提出多种样式和语义修复,但是我建议从您的文件中进行一次通过以获取大小,然后使用它来调用构造函数大小作为参数。然后,您可以在第二次通过中安全地突变这些阵列。这应该让您开始。

最新更新