I compiled my code but it will not output. I get an error that points to
public String toString() { String s= "ALL PACKETS \n"; for(Packet mypacket : shipment) s += mypacket; return s;
it says java.lang.NullException Null...
public class Packet { // instance variables - replace the example below with your own private int idNumber; private String state; public double weight; public Packet(int id, String s, double d) { this.idNumber = id; this.state = s; this.weight = d; } public boolean isHeavy() { if (weight > 12) return true; else return false; } public boolean isLight() { if (weight < 7) return true; else return false; } public String toString() { return "ID: " + idNumber + "\t" + "Weight: " + weight + "\t" + "State: " + state; } }
import java.util.ArrayList; import java.util.Scanner; import java.io.*; public class Packages { double totalWeight; public ArrayList<Packet> shipment; public void Packages () throws IOException { totalWeight = 0.0; shipment = new ArrayList<Packet>(); Scanner fileScan; fileScan = new Scanner (new File("allPackets.txt")); // Read and process each line in the file while (fileScan.hasNext()) { int id = fileScan.nextInt(); String s = fileScan.next(); double d = fileScan.nextDouble(); Packet p = new Packet (id, s, d); shipment.add(p); } System.out.println(shipment); } public void displayLightPackages() { System.out.println("ALL LIGHT PACKAGES \n"); for(Packet mypacket : shipment) if (mypacket.isLight()) System.out.println(mypacket); } public void displayHeavyPackages() { System.out.println("ALL HEAVY PACKETS \n"); for(Packet mypacket : shipment) if (mypacket.isHeavy()) System.out.println(mypacket); } public void displayOtherPackages() { for(Packet mypacket : shipment) if(mypacket.isHeavy() || mypacket.isLight()) System.out.println("ALL REGULAR PACKETS \n"); else System.out.println(mypacket); } public void displayTotalWeight() { for(Packet mypacket : shipment) totalWeight += mypacket.weight; System.out.println ("Total weight of all packets is " + totalWeight); } public void displayAverageWeight() { for(Packet mypacket : shipment) { totalWeight = shipment.size(); } System.out.println("Average weight of all packets is " + totalWeight); } public String toString() { String s= "ALL PACKETS \n"; for(Packet mypacket : shipment) s += mypacket; return s; } }
public class TestPackages { public static void main(String[] args) { Packages mypacket = new Packages(); System.out.println(mypacket); } }
Any help on what I am doing wrong would be great! Thanks.