【问题标题】:Need help finding where this error is coming from需要帮助查找此错误的来源
【发布时间】:2015-11-23 22:59:12
【问题描述】:

这是我在 StackOverflow 上的第一篇文章。 我目前正在编写一个程序,其中我创建了三个程序;客户、宠物和司机。驱动程序从文本文件 (clientdata.txt) 中读取数据。

Client 需要一个 Pets 数组作为字段,而 Clients 和 Pets 列表在文本文件中的排列方式不同,因此需要将其分开。

我遇到问题的代码是当我将数据分成五个客户端的数组和宠物数组时。我尝试时收到 NullPointerException client[count].pet[0] = new Pet(input2[0], input2[1], input2[2], input2[3], input2[4]);而在第一个 for 循环内。 NullPointerException 来自哪里,如何解决?

我需要使用 BlueJ Java 程序。

这是Driver java文件,上面这行代码所在的第一个for循环出现错误。

    import java.util.*;
    import java.io.*;
    import java.util.Scanner;
    /**
      * Write a description of class Driver here.
      * 
      * @author 
      * @version 11-20-15
      */
      public class Driver
      {
        public static void main(String[] args) throws IOException
        {
        Pet[] pet;
        //Client[] client;
        Client[] client = new Client[5];
        String[] input = new String[16];
        String holder;
        String line;
        String line2;
        String line3;
        int line4;
        int line5;
        double line6;
        String fileName;
        Scanner keyboard;
        Scanner dataFile;
        //StringTokenizer token;
        int size1;
        int size2;
        int m = 0;
        int n = 0;
        int count = 0;


   keyboard = new Scanner(System.in);
   //System.out.println("Enter in the size of the pet array: ");
   //size1 = keyboard.nextInt();
  // pet = new Pet[size1];  //must be 16 to work with the given clientdata.txt file
  // System.out.println("Enter in the size of the client array: ");
   //size2 = keyboard.nextInt();

   System.out.println("Please enter in the name of the data file. ");
   fileName = keyboard.nextLine();
   dataFile = new Scanner(new File(fileName));
  // BufferedReader reader = new BufferedReader(fileName);
   while(dataFile.hasNextLine())
   {
       input[m] = dataFile.nextLine();
       m++;
    }
    m = 0;
   ///where to sort data
   while(m < 16)
   {
       String[] data = input[m].split(",");
       client[count] = new Client(data[0],data[1], data[2], data[3], data[4], data[5], data[6]);
       if(client[n].numberOfPets == 1)
       {
         m++;
         String [] input2 = input[m].split(",");
         client[count].pet[0] = new Pet(input2[0], input2[1], input2[2], input2[3], input2[4]);

       }
       else if(client[n].numberOfPets > 1)
       {
           for(int p = 0; p < client[n].numberOfPets; p++)
           {
             m++;
             String [] input2 = input[m].split(",");
             client[count].pet[0] = new Pet(input2[0], input2[1], input2[2], input2[3], input2[4]);  
             //pet = new Pet(input2[0], input2[1], input2[2], input2[3], input2[4]);
            }
       }
    }
    for(int i = 0; i < client[n].numberOfPets; i++)
    {
        System.out.println(client[n].toString());
        for(int i2 = 0; i2 < client[n].numberOfPets; i2++)
        {
            System.out.println(client[n].pet[n].toString());
        }
    }
}

这是客户端 java 文件

        public class Client
        {
private String lastName;
private String firstName;
private String address;
private int clientID;
private int numVisits;
private double balance;
public int numberOfPets;
public Pet[] pet;

public Client()
{
    lastName = new String("unknown");
    firstName = new String("unknown");
    address = new String("unknown");
    clientID = 0;
    numVisits = 0;
    balance = 0;
    numberOfPets = 0;
    pet = null;
}
public Client(String inLast, String inFirst, String inAddress, String inID, String inVisits, String inBalance, String inPet )
{
    lastName = new String(inLast);
    firstName = new String(inFirst);
    address = new String(inAddress);
    clientID = Integer.parseInt(inID);
    numVisits = Integer.parseInt(inVisits);
    balance = Double.parseDouble(inBalance);
    numberOfPets = Integer.parseInt(inPet);
    Pet[] pet = new Pet[numberOfPets];
}
public String toString()
{
   return "\nClient Information: " + lastName + "," + firstName + "," + address + "," + clientID + "," + numVisits + "," + balance;

}
public boolean equals(Client other)
{
    return this.clientID == other.clientID;
}
 }

这是宠物程序

   public class Pet
   {
     private String name;
     private String animalType;
     private double weight;
     private String lastRabiesShot;
     private String lastVisit;

public Pet()
{
    name = new String("unknown");
    animalType = new String("unknown");
    weight = 0;
    lastRabiesShot = new String("unknown");
    lastVisit = new String("unknown");
}
public Pet(String inName, String inType, String inWeight, String inRabies, String inVisit)
{
    name = new String(inName);
    animalType = new String(inType);
    weight = Double.parseDouble(inWeight);
    lastRabiesShot = new String(inRabies);
    lastVisit = new String(inVisit);

}
public String toString()
{
    return "\nPet Information: " + name + "," + animalType + "," + weight + "," + lastRabiesShot + "," + lastVisit;
}
   }

这是示例文本文件(行间没有空格)。

Joe,Johnson,124 Heyo Avenue,15368,4,258.20,2

阿诺德,斗牛犬,58,4-2018-19,6-4-2020

露西,猎犬,14,4-11-2010,5-4-2010

Lewis,Lewis,145 Upchuck Road,78452,3.,185.51,1

布莱克,猫,12,01-6-09,02-09-2011

Miller, Millerson,136 Gunganns Everywhere Drive,96257,2,0.02,3

专业,实验室,102,07-12-2010,07-11-2013

Colonel,Collie,48,02-15-2018,03-15-2008

Captain,Lab,34,02-15-2018,03-15-2008

罗杰斯,史蒂夫,181 Ripoff Marvel Apt B,47895,1,25.08,1

罂粟,猫,104,10-10-2009,10-10-2013

Master,Chief, 343 Unworthy Current Lane,28257,4,343.00,4

Exuberant,Parrot,5,NA,3-13-2014

有罪,德国牧羊犬,88,11-25-2011,11-25-2015

小娜,虎斑猫,15,12-15-2012,05-15-2014

Roland,Collie,8,NA,2-5-2014

如果代码格式看起来有些不妥,我深表歉意。

【问题讨论】:

  • @HovercraftFullOfEels 好的...点了 :-) 无论如何,阅读 tutorial about exceptions 似乎还是不错的读物(我现在正在删除我以前的 cmets)

标签: java arrays nullpointerexception


【解决方案1】:

您在客户端中隐藏了 pet 变量:

class Client {
    // ....
    public Pet[] pet; // it's null here

    public Client() {
        // ...
        pet = null; // here it stays null
    }

    public Client(String inLast, String inFirst, String inAddress, String inID, String inVisits, String inBalance,
            String inPet) {
        // ...
        // here you **re-declare** the variable!!!! Don't do this. 
        Pet[] pet = new Pet[numberOfPets];  // the field remains null!!
    }

不要这样做,不要重新声明它,因为这意味着该字段将始终保持为空。

改变

// you're setting a local variable here, not the pet field
Pet[] pet = new Pet[numberOfPets];

// Now you're setting the pet field
pet = new Pet[numberOfPets];

您的代码还存在其他问题,包括过度使用公共字段,允许外部类直接访问他们随后操作的字段。这可能会增加代码复杂性和副作用,这可能是严重错误的来源。

【讨论】:

  • 谢谢!这有助于修复错误。我知道公共领域的问题,如果可以的话,我会尝试回去解决这个问题。
  • 现在我正在运行代码,我在行 client[count] = new Client(data[0], data[1] 时遇到错误 java.lang.ArrayIndexOutOfBoundsException: 5等等。我知道它是因为 [count] 没有被重申,因为它一直保持在 0。如果我将它放入 for 循环(仅围绕那行代码),错误会转移到 client[count].pet [0] 行。如果我把它放在整个 while 循环中,它会考虑我尝试创建的任何 Pet 对象作为 Client 对象并且在 Pet 构造函数中遇到问题。你知道我该怎么做吗解决这个问题?
  • @RecoveryZero:一个新问题值得一个新问题。但在你问它之前,检查抛出错误的行,检查导致抛出异常的值,搜索类似的问题,然后首先尝试自己修复它。
【解决方案2】:
     m = 0;
       ///where to sort data
       while(m < 16)
       {
           String[] data = input[m].split(",");
           client[count] = new Client(data[0],data[1], data[2], data[3], data[4], data[5], data[6]);
           if(client[n].numberOfPets == 1)
           {
             m++;// **

look at here it starts to read 1, goes to loop check 15<16? yes it moves on m++ made m 16 and here it is you have 15 rows but it is looking for 16th row.

**
             String [] input2 = input[m].split(",");
             client[count].pet[0] = new Pet(input2[0], input2[1], input2[2], input2[3], input2[4]);

           }

【讨论】:

    【解决方案3】:

    client[count].pet[0] = new Pet(input2[0], input2[1], input2[2], input2[3], input2[4]);而在第一个 for 循环内。 NullPointerException 来自哪里,如何解决?

    client 为 null,或 client[count] 为 null,或 client[count].pet 为 null。祝你好运。

    【讨论】:

      猜你喜欢
      • 2011-09-24
      • 1970-01-01
      • 2016-05-25
      • 2013-07-17
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多