我在一个学校项目中工作,我必须在其中使用数组实现递归,并且我已经完成了所有操作,但是当我运行它时出现空错误。错误指向线上的 Recursion 类:
result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination;
我尝试跟踪递归方法以查看它是否真的有意义并且它看起来很可靠,但我仍然得到null error
.
递归类:
import java.io.*;
public class Recursion
{
public String toString(Packet[] packetList, int n)
{
String result = "";
if (n < 0)
{
return result;
}
result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination; // Uncomment if you want the values from last-to-first (last index to 0 index)
result += toString(packetList, n-1);
//result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination; // Uncomment if you want the values from first-to-last (0 index to last index)
return result;
}
}
数据包类
public class Packet
{
public int idNumber;
public double weight;
public String Destination;
public Packet(int id, double w, String D)
{
idNumber = id;
weight = w;
Destination = D;
}
public boolean isHeavy()
{
if (weight > 10)
return true;
else
return false;
}
public String toString()
{
return idNumber + " " + weight + " " + Destination;
}
public double getWeight()
{
return weight;
}
public String getDestination()
{
return Destination;
}
}
测试班
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class TestPackages
{
public static void main (String[] args) throws IOException
{
Packet[] packetList = new Packet[100];
int idNumber;
double weight;
String Destination;
Scanner fileInput;
fileInput = new Scanner (new File("packetData.txt"));
int counter = 0;
while (fileInput.hasNextLine())
{
idNumber = fileInput.nextInt();
weight = fileInput.nextDouble();
Destination = fileInput.nextLine();
Packet myPacket = new Packet (idNumber, weight, Destination);
packetList[counter++] = myPacket;
}
Recursion recursion = new Recursion();
System.out.println(recursion.toString(packetList, packetList.length - 1));
recursion.displayHeavyPackages(packetList, packetList.length - 1);
recursion.displayPacketsToDest(packetList, packetList.length - 1, "CT");
recursion.countPacketsToDest(packetList, packetList.length - 1, "CT");
}
}
看起来您正在将数组的长度发送到您的toString()
函数,但它可能没有初始化 100 个元素,请尝试发送您的“计数器”:
System.out.println(recursion.toString(packetList, counter-1))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句