• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Please help to solve the program with Static Variable & method  RSS feed

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Problem:

Display Shipment Details        
Best Flight is an emerging logistics Company in the City and is evolving the way goods are moved with the power of technology. There are plenty number of Dealers and Customers using Best Flight for shipping their goods. Therefore it essential to connect their Dealers and Customers to Shipment Management System to know the entire details and status of their Shipments. Write a piece of code strictly following the below specifications to get the Shipment details and print the output.  

 This problem will help you understand about Static Variable and Static Method.

Create a class named Shipment with the following private member variables / attributes


   int id
   String shipperName
   String modeOfTransportation
   Float totalWeight
   String arrivalPort
   String departurePort
1. Create a private static variable nextShipmentId in Shipment class and initialise it to 1000.



Hint : static The static variable gets memory only once in class area at the time of class loading. We can apply static keyword with variables, methods, blocks and nested class. The static variable can be used to refer the common property of all objects. It makes your program memory efficient. Eg : static nextShipmentId = 1000;
2. Create a Constructor which accepts 6 arguments in the argument order (id,shipperName,modeOfTransportation,totalWeight,arrivalPort,departurePort)


Hint : Constructor A constructor in Java is a block of code similar to a method that's called when an instance of an object is created. A constructor doesn't have a return type. Eg : public Shipment(id,shipperName,modeOfTransportation,totalWeight,arrivalPort,departurePort)
3. Create a static method createNewShipment() - which accepts the shipment details in the parameter and generates the shipment object and assigns the shipment id and return the shipment object. For returning the object pass the values in the constructor and return it.


public static Shipment createNewShipment(String shipperName,String modeOfTransportation,Float totalWeight,String arrivalPort,String departurePort)
The id assigned to each shipment must be unique and it must be in order. The first shipment should have the id as 1001, the next shipment should have the id as 1002 and so on.


Hint : return Type Declare a method's return type in its method declaration. Within the body of the method, use the return statement to return the value. Any method declared void doesn't return a value. Eg : public static Shipment createNewShipment(){  return returnValue; }
4. Display the shipment details by overriding the toString() method in Shipment class.
Use String.format("%-15d%-15s%-25s%-15s%-20s%s",this.id,this.shipperName,this.modeOfTransportation,this.totalWeight.toString()+"Kg",this.arrivalPort,this.departurePort)  to format the string.

Hint : toString() The toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String  representation of the Object. Eg : public String toString() {  // return the formatted String. - Override the toString() method here }
Create a Main Class and write a main method in it and test the above class.

Problem Specification :
The toString() method will overrides the object representation into required format. If we try to print the object, the toString() method will be automatically invoked and the changed representation of the string will be printed as shown in Sample input and Output.
Print the "Shipment details are" String and the table header details in main method itself. The toString() method will only contain the format for printing the object.

[Note :Strictly adhere to the object oriented specifications given as a part of the problem statement.Use the same class names, attribute names and method names.]



Input and Output Format:
Refer sample input and output for formatting specifications.

Sample Input and Output :
[All text in bold corresponds to the input and the rest corresponds to output.]
Enter the number of shipments :
3
Enter the shipment 1 details
Enter the shipper name :
AGCI
Enter the mode of transportation :
Air
Enter the total weight :
300
Enter the arrival port :
India
Enter the departure port :
America
Enter the shipment 2 details
Enter the shipper name :
DHL Services
Enter the mode of transportation :
Water
Enter the total weight :
500
Enter the arrival port :
Cochin
Enter the departure port :
Srilanka
Enter the shipment 3 details
Enter the shipper name :
Fedex
Enter the mode of transportation :
Land
Enter the total weight :
200
Enter the arrival port :
India
Enter the departure port :
China
Shipment details are
Id                 Shippername            Mode of transportation   Total weight   Arrival port        Departure port          
1001           AGCI                               Air                                                    300Kg                India                      America            
1002           DHL Services            Water                                            500Kg               Cochin                  Srilanka            
1003           Fedex                             Land                                              200Kg                India                      China
 
Marshal
Posts: 61690
192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

How far have you got with that assignment? There is a great deal of detail in that instruction, which shou‍ld be easy enough to follow. Do you mean the static method which creates an instance? That sounds like a factory method, which you can read about in Effective Java by Joshua Bloch (page 5) or you can read about i lots of places; Wikipedia will doubtless have a good example.

Did it really say Float for weight? Not float? You will have to follow that, but I would never use a float if I can help it.
 
tk bharathi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marshal,

Thanks a lot for your support in learning. Yes you are correct.It is float.

I am started learning java.

But for me, this problem is much tricky

I wrote few lines. I struck with below.

 
Campbell Ritchie
Marshal
Posts: 61690
192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, that code is perfectly all right. You could improve the formatting, however, maybe following our suggestions here. I added code tags and doesn't it look better Always use the code tags. The many parameters required made some lines too long, but you can see in the new version how to correct that. You would have done it more neatly than I did.

Your create instance method won't compile because it is incomplete, but I suggest you write down what that method is supposed to do. Or tell a friend. I think that may inspire you to work out what to write in that method.
Were you given any instructions about access modifiers for the constructor? If you make it private, you can use the factory method as the only way to create instances outside the current class. A factory method is called to create an instance and return a reference to it, and there may be no instances in existence before the factory method is called. That is why factory methods are usually static; they exist before any instances were created.
 
tk bharathi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell. Could you please me in writing the content in public static Shipment createNewShipment() method.
 
Campbell Ritchie
Marshal
Posts: 61690
192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We don't hand out solutions. As I said, please write down what that method is supposed to do. Don't copy what the question says, but you are allowed to look at it.
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, All,

Can someone help me to figure out the issue and solve it

Class: Shipment

package Classesandobjects1;

import java.util.Scanner;

public class Shipment
   
{
private int id;
   private String shipperName;
   private String modeOfTransportation;
   private Float totalWeight;
   private String arrivalPort;
   private String departurePort;
   private static int nextShipment;



    Shipment(int nextShipment, String shipperName, String modeOfTransportation,
               Float totalWeight, String arrivalPort, String departurePort)
   {
       this.nextShipment = 1001;
       this.shipperName = shipperName;
       this.modeOfTransportation = modeOfTransportation;
       this.totalWeight = totalWeight;
       this.arrivalPort = arrivalPort;
       this.departurePort = departurePort;
   }












public static Shipment createNewShipment(int nextShipment, String shipperName, String modeOfTransportation,
               Float totalWeight, String arrivalPort, String departurePort)
{

       Shipment shipment = new Shipment(nextShipment, shipperName, modeOfTransportation, totalWeight, arrivalPort, departurePort);
       nextShipment++;
       return shipment;
       
   }




public String toString()
{    System.out.println("Shipment details are");
System.out.format("%-15s%-15s%-25s%-15s%-20s%s\n","Id","Shippername","Mode of transportation","Total weight","Arrival port","Departure port");
return String.format(String.format("%-15s%-15s%-25s%-15s%-20s%s",this.id,this.getShipperName(),this.getModeOfTransportation(),this.getTotalWeight().toString()+"Kg",this.getArrivalPort(),this.getDeparturePort()));

}

 

public String getShipperName() {
return shipperName;
}
public void setShipperName(String shipperName) {
this.shipperName = shipperName;
}
public String getModeOfTransportation() {
return modeOfTransportation;
}
public void setModeOfTransportation(String modeOfTransportation) {
this.modeOfTransportation = modeOfTransportation;
}
public Float getTotalWeight() {
return totalWeight;
}
public void setTotalWeight(Float totalWeight) {
this.totalWeight = totalWeight;
}
public String getArrivalPort() {
return arrivalPort;
}
public void setArrivalPort(String arrivalPort) {
this.arrivalPort = arrivalPort;
}
public String getDeparturePort() {
return departurePort;
}
public void setDeparturePort(String departurePort) {
this.departurePort = departurePort;
}

}




Class2: Main
package Classesandobjects1;


import java.util.InputMismatchException;
import java.util.Scanner;

public class Main1 {

   public static void main(String[] args) {
    // TODO Auto-generated method stub
    Shipment s1 = new Shipment(0, null, null, null, null, null);
   
    System.out.println("Enter the number of shipments :");
Scanner Sc =  new Scanner(System.in);
int n = Sc.nextInt();
for(int i=1;i<=n;i++)
{

       System.out.println("Enter the shipment " +i+ " details");
System.out.println("Enter the shipper name :");
s1.setShipperName(Sc.next());
System.out.println("Enter the mode of transportation :");
s1.setModeOfTransportation(Sc.next());
System.out.println("Enter the total weight :");
s1.setTotalWeight(Sc.nextFloat());
System.out.println("Enter the arrival port :");
    s1.setArrivalPort(Sc.next());
System.out.println("Enter the departure port :");
s1.setDeparturePort(Sc.next());
}
     

s1.toString();





}
}



Expected Output:
Shipment details are
Id                 Shippername            Mode of transportation   Total weight   Arrival port        Departure port          
1001           AGCI                               Air                                                    300Kg                India                      America            
1002           DHL Services            Water                                            500Kg               Cochin                  Srilanka            
1003           Fedex                             Land                                              200Kg                India                      China




Actual Output:
Shipment details are
Id             Shippername    Mode of transportation   Total weight   Arrival port        Departure port
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here you go bro,

import java.util.Scanner;

class Shipment{

private int id;
private String shipperName;
private String modeOfTransportation;
private Float totalWeight;
private String arrivalPort;
private String departurePort;

static int nextShipmentId = 1000;

public Shipment (int id, String shipperName, String modeOfTransportation, Float totalWeight, String arrivalPort, String departurePort){

this.id = id;
this.shipperName = shipperName;
this.modeOfTransportation = modeOfTransportation;
this.totalWeight = totalWeight;
this.arrivalPort= arrivalPort;
this.departurePort = departurePort;

}

public static Shipment createNewShipment (String shipperName, String modeOfTransportation, Float totalWeight, String arrivalPort, String departurePort) {

Shipment ship3 = new Shipment(++nextShipmentId, shipperName, modeOfTransportation, totalWeight, arrivalPort, departurePort);
return ship3;
}


public String toString() {
return String.format("%-15d%-15s%-25s%-15s%-20s%s",this.id,this.shipperName,this.modeOfTransportation,this.totalWeight.toString()+"Kg",this.arrivalPort,this.departurePort);
}

}

public class ClassObjects2 {

public static void main(String[] args) {

Scanner scan = new Scanner (System.in);
System.out.println("Enter the number of shipments :");
int nships = Integer.parseInt(scan.nextLine());

String[] shipperName =  new String[nships];
String[] modeTrans = new String[nships];
String[] aPort = new String[nships];
String[] dPort = new String[nships];
Float[] tWeight = new Float[nships];
Shipment[] ship = new Shipment[nships];

for (int i=0; i<nships; i++) {
System.out.println("Enter the shipment " + (i+1) + " deails");
System.out.println("Enter the shipper name :");
shipperName[i] = scan.nextLine();
System.out.println("Enter the mode of transportation :");
modeTrans[i] = scan.nextLine();
System.out.println("EEnter the total weight :");
tWeight[i] = Float.parseFloat(scan.nextLine());
System.out.println("Enter the arrival port :");
aPort[i] = scan.nextLine();
System.out.println("Enter the departure port :");
dPort[i] = scan.nextLine();
ship[i] = Shipment.createNewShipment(shipperName[i], modeTrans[i], tWeight[i], aPort[i], dPort[i]);
}

scan.close();

System.out.println("Shipment details are");
System.out.format("%-15s%-15s%-25s%-15s%-20s%s","Id", "Shippername", "Mode of transportation", "Total Weight", "Arrival port", "Departure port");
System.out.println();

for (int i=0; i<nships; i++)
System.out.println(ship[i].toString());


}

}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!