I need help getting the methods in class Packages to work and output. The toStri
ID: 440651 • Letter: I
Question
I need help getting the methods in class Packages to work and output.
The toString function outputs my array. I just need the methods like displayLightPackages to output as well. Any help?
public class Packet
{
// instance variables - replace the example below with your own private
int idNumber;
public double weight;
private String state;
public Packet(int id, double d, String s)
{
this.idNumber = id;
this.weight = d;
this.state = s;
}
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()
{
String s = "ID: " + idNumber + " " + "Weight: " + weight + " " + "State: " + state; return s;
}
}
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class Packages
{
double totalWeight;
public ArrayList shipment;
public Packages () throws IOException
{
totalWeight = 0.0; shipment = new ArrayList();
String currentPacket;
Scanner fileScan, packetScan;
fileScan = new Scanner (new File("allPackets.txt"));
// Read and process each line in the file
while (fileScan.hasNext())
{
currentPacket = fileScan.nextLine(); packetScan = new Scanner (currentPacket);
int id = packetScan.nextInt();
double d = packetScan.nextDouble();
String s = packetScan.next();
Packet temp = new Packet (id,d,s);
shipment.add(temp);
}
System.out.println(shipment);
}
public void displayLightPackages()
{ for(Packet thepacket : shipment)
if (thepacket.isLight()) System.out.println("ALL LIGHT PACKAGES " + thepacket);
}
public void displayHeavyPackages()
{
for(Packet thepacket : shipment)
if (thepacket.isHeavy()) System.out.println("ALL HEAVY PACKETS " + thepacket);
}
public void displayOtherPackages()
{
for(Packet thepacket : shipment) if(thepacket.isHeavy() || thepacket.isLight())
System.out.println("ALL REGULAR PACKETS ");
else System.out.println(thepacket);
}
public void displayTotalWeight()
{ for(Packet thepacket : shipment)
totalWeight += thepacket.weight;
System.out.println ("Total weight of all packets is " + totalWeight);
}
public void displayAverageWeight()
{
for(Packet thepacket : shipment)
{
totalWeight = shipment.size();
System.out.println("Average weight of all packets is " + totalWeight);
}
}
public String toString()
{
String s = "ALL PACKETS "; for(Packet thepacket : shipment) s += thepacket + " ";
return s;
}
}
Explanation / Answer
If you want any particular function to produce the output, you can simply use cout in that function code. There would be no problem at all. Instead of printing in the main function, cout works for any function. For eg: you can use coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.