Hey i want to loop through planes to get all passengers and add them to a count to display all passengers for all planes. But im getting an error: Cannot iterate over an array or an instance.
Here is the method:
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : plane.getPassengerNumber())
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
Plane
import java.util.LinkedList;
public class Plane implements Comparable
{
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
private boolean isLanded = false;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
public Plane(String flightNumber, String airlineName,
double fuelRemaining, int overdue, int passengerNumber,
AIRPLANETYPE planeType, boolean isLanded)
{
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
this.isLanded = isLanded;
}
public Plane()
{
}
public String getAirlineName() {
return airlineName;
}
public void setAirlineName(String airlineName) {
this.airlineName = airlineName;
}
public void setOverdue(int overdue) {
this.overdue = overdue;
}
public int getOverdue(){
return overdue;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public boolean isLanded() {
return isLanded;
}
public void setLanded(boolean isLanded) {
this.isLanded = isLanded;
}
public int compareTo(Object arg0) {
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.overdue - p.getOverdue());
}
return 0;
}
public String toString() {
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType +
"hasLanded=" + isLanded+ ".\n";
}
}
passengerNumber is an int. You need to iterate over an Iterable such as an ArrayList:
for (Plane plane: myPlaneList) {
passengers += plane.getPassengerNumber();
}
You are trying to iterate through Plane objects, but your collection is just an int. You'll need a collection of Plane objects
int passengers = 0;
for(Plane plane : myPlanes)
{
passengers += plane.getPassengerNumber();
}
You are trying to iterate over an int, you need to iterate over an java.util.Iterable
Your posted code does not contain the information needed to answer this question.
You are showing us the class Plane, but in order to have more than one plane, you probably have a List<Plane> or a Plane[] somewhere else in the code. Here's one example that would work:
public class Main {
List<Plane> allPlanes; // Load in the omitted code somewhere else
public int getAllPassengers()
{
int passengers = 0;
for(Plane plane : allPlanes) // note the change
{
passengers += plane.getPassengerNumber();
}
return passengers;
}
}
Related
I have a car class and its constructor looks like this:
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
this.position = position;
this.assignedTo = assignedTo;
this.currTime = currTime;
}
The constructor is initialized in another class(main) when I press for create car from the menu.
The parameters of the constructor are all created/initiated by methods in the car class. The system should be the one giving the information like(the ID, position and time in).
The problem is that the car object have not be initialized yet so I can't get the methods to work.
But I really need the cars object to contain its information(like car ID:CR1).
The information are all strings except for the time.
How can I do that?
PS: Im new to programming. At first I was using static but it turns out static methods cause another bigger trouble with my code.
I posted something where there was my static methods and everyone told me to remove the statics.
public void addCar() {
Cars car1 = new Cars(car1.getID(), car1.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car1);
if(!(car1.getAssignedTo()).equals(null)){
car1.getAssignedTo().setAssign(car1);
car1.getAssignedTo().setAvailable(false);
}
}
This is what is called when I want to create a new car.
I also put the whole car class in case you need it:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import javax.swing.text.Position;
public class Cars {
private String carID;
private String plateNum;
private String position;
private Attendant assignedTo;
private long currTime;
static ArrayList<String> tempArray2 = new ArrayList<String>();
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
this.position = position;
this.assignedTo = assignedTo;
this.currTime = currTime;
}
public void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
String tempCarID = ("CR" + (x + 1));
tempArray2.add(tempCarID);
}
}
public String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
tempArray2.remove(tempArray2.get(x));
getPos(tempPos);
//tempArray2.get(x) = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public static String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
#Override
public String toString() {
return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId()
+ "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}
}
I attach you a code that can help you:
first as all the parameters can be statics i move then to the constructor.
second i move the static method "createCarsID();" to a static init block, in order to avoid unwanted calls.
The example is fully functional.
package test;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import javax.swing.text.Position;
public class Cars {
private String carID;
private String plateNum;
private String position;
private Attendant assignedTo;
private long currTime;
static ArrayList<String> tempArray2 = new ArrayList<String>();
static{
createCarsID();
}
public Cars() {
this.carID = Cars.getID();
this.plateNum = Cars.askCarID();
this.position = Cars.generatePosition();
this.assignedTo = Attendant.askForAtt();
this.currTime = System.currentTimeMillis();
}
public static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
String tempCarID = ("CR" + (x + 1));
tempArray2.add(tempCarID);
}
}
public static String getID() {
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
//tempArray2.remove(tempArray2.get(x));
//getPos(tempPos);
//tempArray2.get(x) = null;
break;
}
}
return tempID;
}
public static String generatePosition() {
String tempID = null;
String tempPos = null;
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
if (tempArray2.get(x) != null) {
tempID = tempArray2.get(x);
tempPos = tempArray2.get(x);
tempArray2.remove(tempArray2.get(x));
return getPos(tempPos);
//tempArray2.get(x) = null;
}
}
return null;
}
public static String getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
return "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
#Override
public String toString() {
return "Car:" + plateNum + " ID:" + carID + " Position:" + position + " Assigned to:" + assignedTo.getId()
+ "(" + assignedTo.getName() + ")" + " Parked at:" + convert(currTime);
}
}
Finally in order to call this function:
package test;
public class main {
public static void main(String [] args){
main test = new main();
test.addCar();
}
public void addCar() {
Cars car1 = new Cars();
Garage myGarage = new Garage();
myGarage.add(car1);
if(!(car1.getAssignedTo()).equals(null)){
car1.getAssignedTo().setAssign(car1);
car1.getAssignedTo().setAvailable(false);
}
}
}
how to find the best route for multiple locations in google maps api in android? I have some locations as LatLng but I dont know how specify a optimal route
ArrayList<LatLng> directionPoint = latLongList;
PolylineOptions rectLine = new PolylineOptions().width(8).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
Try this , pass your list of latlongs in latLongList
Using Google maps direction api you can acheive it, follow the documentation about using waypoints -
https://developers.google.com/maps/documentation/directions/intro#Waypoints
Now a fully functional api looks like this -
https://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&key=YOUR_API_KEY
Here origin = starting point, destination = Ending point, waypoints = points that you want to cover, optimize:true = the route through the given waypoints will be optimized(i.e following Traveling Salesman Problem) and key = your map api key.
Now in order to save the api response here is the model class -
public class DirectionApiResponse {
private ArrayList<Geocoded_waypoints> geocoded_waypoints;
private String status;
private ArrayList<Routes> routes;
public ArrayList<Geocoded_waypoints> getGeocoded_waypoints ()
{
return geocoded_waypoints;
}
public void setGeocoded_waypoints (ArrayList<Geocoded_waypoints> geocoded_waypoints)
{
this.geocoded_waypoints = geocoded_waypoints;
}
public String getStatus ()
{
return status;
}
public void setStatus (String status)
{
this.status = status;
}
public ArrayList<Routes> getRoutes ()
{
return routes;
}
public void setRoutes (ArrayList<Routes> routes)
{
this.routes = routes;
}
#Override
public String toString()
{
return "ClassPojo [geocoded_waypoints = "+geocoded_waypoints+", status = "+status+", routes = "+routes+"]";
}
public class Geocoded_waypoints
{
private String place_id;
private String geocoder_status;
private ArrayList<String> types;
public String getPlace_id ()
{
return place_id;
}
public void setPlace_id (String place_id)
{
this.place_id = place_id;
}
public String getGeocoder_status ()
{
return geocoder_status;
}
public void setGeocoder_status (String geocoder_status)
{
this.geocoder_status = geocoder_status;
}
public ArrayList<String> getTypes ()
{
return types;
}
public void setTypes (ArrayList<String> types)
{
this.types = types;
}
#Override
public String toString()
{
return "ClassPojo [place_id = "+place_id+", geocoder_status = "+geocoder_status+", types = "+types+"]";
}
}
public class Routes {
private String summary;
private Bounds bounds;
private String copyrights;
private ArrayList<String> waypoint_order;
private ArrayList<Legs> legs;
private ArrayList<String> warnings;
private Overview_polyline overview_polyline;
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Bounds getBounds() {
return bounds;
}
public void setBounds(Bounds bounds) {
this.bounds = bounds;
}
public String getCopyrights() {
return copyrights;
}
public void setCopyrights(String copyrights) {
this.copyrights = copyrights;
}
public ArrayList<String> getWaypoint_order() {
return waypoint_order;
}
public void setWaypoint_order(ArrayList<String> waypoint_order) {
this.waypoint_order = waypoint_order;
}
public ArrayList<Legs> getLegs() {
return legs;
}
public void setLegs(ArrayList<Legs> legs) {
this.legs = legs;
}
public ArrayList<String> getWarnings() {
return warnings;
}
public void setWarnings(ArrayList<String> warnings) {
this.warnings = warnings;
}
public Overview_polyline getOverview_polyline() {
return overview_polyline;
}
public void setOverview_polyline(Overview_polyline overview_polyline) {
this.overview_polyline = overview_polyline;
}
#Override
public String toString() {
return "ClassPojo [summary = " + summary + ", bounds = " + bounds + ", copyrights = " + copyrights + ", waypoint_order = " + waypoint_order + ", legs = " + legs + ", warnings = " + warnings + ", overview_polyline = " + overview_polyline + "]";
}
public class Bounds
{
private Southwest southwest;
private Northeast northeast;
public Southwest getSouthwest ()
{
return southwest;
}
public void setSouthwest (Southwest southwest)
{
this.southwest = southwest;
}
public Northeast getNortheast ()
{
return northeast;
}
public void setNortheast (Northeast northeast)
{
this.northeast = northeast;
}
#Override
public String toString()
{
return "ClassPojo [southwest = "+southwest+", northeast = "+northeast+"]";
}
public class Southwest
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
public class Northeast
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
}
public class Overview_polyline {
private String points;
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
#Override
public String toString() {
return "ClassPojo [points = " + points + "]";
}
}
public class Legs {
private Duration duration;
private Distance distance;
private End_location end_location;
private String start_address;
private String end_address;
private Start_location start_location;
private ArrayList<String> traffic_speed_entry;
private ArrayList<String> via_waypoint;
private ArrayList<Steps> steps;
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public End_location getEnd_location() {
return end_location;
}
public void setEnd_location(End_location end_location) {
this.end_location = end_location;
}
public String getStart_address() {
return start_address;
}
public void setStart_address(String start_address) {
this.start_address = start_address;
}
public String getEnd_address() {
return end_address;
}
public void setEnd_address(String end_address) {
this.end_address = end_address;
}
public Start_location getStart_location() {
return start_location;
}
public void setStart_location(Start_location start_location) {
this.start_location = start_location;
}
public ArrayList<String> getTraffic_speed_entry() {
return traffic_speed_entry;
}
public void setTraffic_speed_entry(ArrayList<String> traffic_speed_entry) {
this.traffic_speed_entry = traffic_speed_entry;
}
public ArrayList<String> getVia_waypoint() {
return via_waypoint;
}
public void setVia_waypoint(ArrayList<String> via_waypoint) {
this.via_waypoint = via_waypoint;
}
public ArrayList<Steps> getSteps() {
return steps;
}
public void setSteps(ArrayList<Steps> steps) {
this.steps = steps;
}
#Override
public String toString() {
return "ClassPojo [duration = " + duration + ", distance = " + distance + ", end_location = " + end_location + ", start_address = " + start_address + ", end_address = " + end_address + ", start_location = " + start_location + ", traffic_speed_entry = " + traffic_speed_entry + ", via_waypoint = " + via_waypoint + ", steps = " + steps + "]";
}
public class Duration {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", value = " + value + "]";
}
}
public class Start_location
{
private String lng;
private String lat;
public String getLng ()
{
return lng;
}
public void setLng (String lng)
{
this.lng = lng;
}
public String getLat ()
{
return lat;
}
public void setLat (String lat)
{
this.lat = lat;
}
#Override
public String toString()
{
return "ClassPojo [lng = "+lng+", lat = "+lat+"]";
}
}
public class End_location {
private String lng;
private String lat;
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
#Override
public String toString() {
return "ClassPojo [lng = " + lng + ", lat = " + lat + "]";
}
}
public class Distance {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return "ClassPojo [text = " + text + ", value = " + value + "]";
}
}
public class Steps
{
private String html_instructions;
private Duration duration;
private Distance distance;
private End_location end_location;
private Polyline polyline;
private Start_location start_location;
private String travel_mode;
public String getHtml_instructions ()
{
return html_instructions;
}
public void setHtml_instructions (String html_instructions)
{
this.html_instructions = html_instructions;
}
public Duration getDuration ()
{
return duration;
}
public void setDuration (Duration duration)
{
this.duration = duration;
}
public Distance getDistance ()
{
return distance;
}
public void setDistance (Distance distance)
{
this.distance = distance;
}
public End_location getEnd_location ()
{
return end_location;
}
public void setEnd_location (End_location end_location)
{
this.end_location = end_location;
}
public Polyline getPolyline ()
{
return polyline;
}
public void setPolyline (Polyline polyline)
{
this.polyline = polyline;
}
public Start_location getStart_location ()
{
return start_location;
}
public void setStart_location (Start_location start_location)
{
this.start_location = start_location;
}
public String getTravel_mode ()
{
return travel_mode;
}
public void setTravel_mode (String travel_mode)
{
this.travel_mode = travel_mode;
}
#Override
public String toString()
{
return "ClassPojo [html_instructions = "+html_instructions+", duration = "+duration+", distance = "+distance+", end_location = "+end_location+", polyline = "+polyline+", start_location = "+start_location+", travel_mode = "+travel_mode+"]";
}
public class Polyline
{
private String points;
public String getPoints ()
{
return points;
}
public void setPoints (String points)
{
this.points = points;
}
#Override
public String toString()
{
return "ClassPojo [points = "+points+"]";
}
}
}
}
}
}
Now to draw the route in between way-points you can use the below method -
private void setRoutePath(DirectionApiResponse directionObj){
gMap.clear();
addMarkers(localLeedsArrayList);
int count = 0;
ArrayList<LatLng> points = null;
DirectionApiResponse.Routes route = directionObj.getRoutes().get(0);
// Traversing through all the routes
for(DirectionApiResponse.Routes.Legs leg : route.getLegs()){
PolylineOptions lineOptions = new PolylineOptions();
points = new ArrayList<LatLng>();
Log.e("Route", leg.getStart_address()+" "+leg.getEnd_address());
// Fetching all the points in i-th route
//for(DirectionApiResponse.Routes.Legs.Steps step : leg.getSteps()){
for(int j=0;j<leg.getSteps().size();j++){
DirectionApiResponse.Routes.Legs.Steps step = leg.getSteps().get(j);
points.addAll(PolyUtil.decode(step.getPolyline().getPoints()));
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(20);
lineOptions.color(colors[count]);
Polyline polylineFinal = gMap.addPolyline(lineOptions);
count++;
}
Log.e("SouthWest",directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng());
Log.e("northeast",directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()+" "+directionObj.getRoutes().get(0).getBounds().getNortheast().getLng());
/*LatLng lSouth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLat()),
Double.valueOf(directionObj.getRoutes().get(0).getBounds().getSouthwest().getLng()));
LatLng lNorth = new LatLng(Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLat()),
Double.valueOf(directionObj.getRoutes().get(0).getBounds().getNortheast().getLng()));
LatLngBounds latLngBounds = new LatLngBounds(lNorth,lSouth);
gMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,14));*/
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude()),15));
}
Here gMap is the google map object..
******* UPDATE Api Calling********
In order to call the api Create interface IApiMethods and put the code below -
#GET("json?origin=35.693391,51.424261&destination=35.692032,51.432715&waypoints=35.691997,51.432758")
Call<DirectionApiResponse> getDirectionWalking(#Query("key")String key);
you can change the co-ordinates accordingly
Now call the method below to call the api and get the DirectionApiResponse object
private void getDirection(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/api/directions/")
.addConverterFactory(GsonConverterFactory.create())
.build();
IApiMethods service = retrofit.create(IApiMethods.class);
Call<DirectionApiResponse> directionApiResponseCall = service.getDirectionWalking("YOUR API KEY");
directionApiResponseCall.enqueue(new Callback<DirectionApiResponse>() {
#Override
public void onResponse(Call<DirectionApiResponse> call, Response<DirectionApiResponse> response) {
setRoutePath(response.body());
}
#Override
public void onFailure(Call<DirectionApiResponse> call, Throwable t) {
}
});
}
Finally add the following dependencies to the app's build.gradle file -
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
How to get the route
You might want to look at the Distance Matrix service: https://developers.google.com/maps/documentation/javascript/distancematrix
It gives you distances between a set of origins and destinations, and might help you with narrowing down options.
2. To Find the best route :
If using the web service, ensure you set optimize:true before listing your waypoints, and check the waypoint_order array.
http://maps.googleapis.com/maps/api/directions/json?origin=Adelaide,SA&destination=Adelaide,SA&waypoints=optimize:true|Barossa+Valley,SA|Clare,SA|Connawarra,SA|McLaren+Vale,SA&sensor=false
If use the JS API, set optimizeWaypoints:true in your request.
3. To draw polyline with the latlongs you have
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);
I'm having a problem regarding a polymorphic invocation inside a loop.
I have an abstract class called Item that has two subclasses ClothingItem and SportItem and an abstract method called printBudgetGST(Items[] item) to return a string of an item with updated pricing which include tax.
Item Class :
public abstract class Item
{
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST(Item[] items);
}
ClothingItem class
public class ClothingItem extends Item
{
public ClothingItem(){
}
public ClothingItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
#Override
public String printBudgetGST(Item[] item)
{
String stringitem ="";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true&&item[i].getCurrentPrice()<100.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
SportsItem class:
public class SportsItem extends Item
{
public SportsItem(){
}
public SportsItem(int code,double price,boolean isOnGST)
{
super(code,price,isOnGST);
}
public String printBudgetGST(Item[] item)
{
String stringitem = "";
for(int i=0;i<item.length;i++)
{
if(item[i].getIsOnGST()==true &&item[i].getCurrentPrice()<150.00)
{
double finalprice =(0.06*item[i].getCurrentPrice())+item[i].getCurrentPrice();
stringitem = stringitem + "SportsItem : " + item[i].getCode()+":"+"RM"+finalprice;
}
}
return stringitem;
}
}
Test class :
public class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem()
{
for(int i =0 ;i<itemList.length;i++)
{
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST(itemList).length()>0)
{
System.out.println(itemList[i].printBudgetGST(itemList));
}
}
}
}
public class TestRetailItem {
public static void main(String[] args)
{
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
OUTPUT :
The output should return a list of items which is on tax(GST) and with the updated pricing information like the example below
The problem is that you are passing to printBudgetGST the whole array of items and iterating over that array inside your implementations of printBudgetGST. Instead, you should remove that parameter and inside printBudgetGST you should simply call getCurrentPrice() and getCode() on this rather than on each item[i].
In addition, you are doing the check for maximum price (< 100 or < 150) inside the item subclasses but it's best to do this alongside the other checks in printItem. Because the max price depends on the subclass (SportsItem vs ClothinItem) I recommend you to create an abstract method boolean isOnBudget() in Item and implement accordingly in those two subclasses.
A fully fixed version of your code is
public abstract class Item {
private int code;
private double price;
private boolean isOnGST;
public Item()
{
}
public Item(int code,double price,boolean isOnGST)
{
this.code = code;
this.price = price;
this.isOnGST = isOnGST;
}
public void setGST(boolean isgst)
{
this.isOnGST = isgst;
}
public int getCode()
{
return code;
}
public boolean getIsOnGST()
{
return isOnGST;
}
public double getCurrentPrice()
{
return price;
}
public String toString() {
return "Item [code=" + code + ", price=" + price + ", isOnGST=" + isOnGST + "]";
}
public abstract String printBudgetGST();
public abstract boolean isOnBudget();
}
class ClothingItem extends Item {
public ClothingItem() {
}
public ClothingItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
#Override
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + " " + "ClothingItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 100.00;
}
}
class SportsItem extends Item {
public SportsItem() {
}
public SportsItem(int code, double price, boolean isOnGST) {
super(code, price, isOnGST);
}
public String printBudgetGST() {
String stringitem = "";
double finalprice = (0.06 * getCurrentPrice()) + getCurrentPrice();
stringitem = stringitem + "SportsItem : " + getCode() + ":" + "RM" + finalprice;
return stringitem;
}
#Override
public boolean isOnBudget() {
return getCurrentPrice() < 150.00;
}
}
class Retail_Item
{
private Item[] itemList;
public Retail_Item()
{
itemList = new Item[10];
itemList[0] = new ClothingItem(10001,85,true);
itemList[1] = new ClothingItem(10002,150,false);
itemList[2] = new ClothingItem(10003,168,true);
itemList[3] = new ClothingItem(10004,43,true);
itemList[4] = new ClothingItem(10005,162,false);
itemList[5] = new SportsItem(10006,178,false);
itemList[6] = new SportsItem(10007,80,true);
itemList[7] = new SportsItem(10008,191,false);
itemList[8] = new SportsItem(10009,45,true);
itemList[9] = new SportsItem(10010,121,true);
}
public void printItem() {
for(int i =0 ;i<itemList.length;i++) {
if(itemList[i].getIsOnGST()==true && itemList[i].printBudgetGST().length()>0 && itemList[i].isOnBudget())
{
System.out.println(itemList[i].printBudgetGST());
}
}
}
}
class TestRetailItem {
public static void main(String[] args) {
Retail_Item ret = new Retail_Item();
ret.printItem();
}
}
public class ParkedCar {
private String make;
private String model;
private String color;
private String licenseNum;
public ParkedCar(String make, String model, String color, String licenseNum) {
this.make = make;
this.model = model;
this.color = color;
this.licenseNum = licenseNum;
}
public void setMake(String ma) {
make = ma;
}
public void setModel(String mo) {
model = mo;
}
public void setColor(String c) {
color = c;
}
public void setLicenseNum(String ln) {
licenseNum = ln;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public String getLicenseNum() {
return licenseNum;
}
}
public class ParkingMeter {
private ParkedCar parkedcar;
private int timePurchased;
private int timeParked;
public ParkingMeter(ParkedCar parkedcar, int timePurchased, int timeParked) {
this.parkedcar = parkedcar;
this.timePurchased = timePurchased;
this.timeParked = timeParked;
}
/*public ParkingMeter (ParkedCar parkedcar) {
this.parkedcar = null;
}*/
public void setTimePurchased(int timePurchased) {
this.timePurchased = timePurchased;
}
public int getTimePurchased() {
return timePurchased;
}
public void setTimeParked(int timeParked) {
this.timeParked = timeParked;
}
public int getTimeParked() {
return timeParked;
}
public int TimeExpired() {
if (timeParked > timePurchased)
return timeParked - timePurchased;
else
return 0;
}
public String toString() {
return "Make: " + parkedcar.getMake() + "\nModel: " + parkedcar.getModel() + "\nColor: " + parkedcar.getColor() + "\nLicense Number: " + parkedcar.getLicenseNum();
}
}
public class ParkingTicket {
private ParkingMeter parkingmeter;
public ParkingTicket(ParkingMeter parkingmeter) {
this.parkingmeter = parkingmeter;
}
public int TicketCost() {
if (parkingmeter.getTimeParked() > parkingmeter.getTimePurchased()) {
if (parkingmeter.getTimeParked() <= 60)
return 25;
else
return 25 + (10*(parkingmeter.TimeExpired())/60);
}
else
return 0;
}
}
public class PoliceOfficer {
private String OfficerName;
private int OfficerNum;
private ParkingMeter pm;
private ParkingTicket pt;
public PoliceOfficer(ParkingTicket pt, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
public void setOfficerName(String OfficerName) {
this.OfficerName = OfficerName;
}
public void setOfficerNum(int OfficerNum) {
this.OfficerNum = OfficerNum;
}
public String getOfficerName() {
return OfficerName;
}
public int getOfficerNum() {
return OfficerNum;
}
public boolean isExpired() {
if (pm.getTimeParked() > pm.getTimePurchased())
return true;
else
return false;
}
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
}
public class ParkingTicketDemo {
public static void main(String[] args) {
ParkedCar pc = new ParkedCar("Toyota", "Camry", "Blue", "BXZ 152");
System.out.println(pc);
ParkingMeter pm = new ParkingMeter(pc, 60, 120);
ParkingTicket pt = new ParkingTicket(pm);
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
}
}
I have been trying to create a program to create and issue a parking ticket and have run into the problem where it compiles, but when it runs it gives out the error message Exception in thread "main" java.lang.NullPointerException. I am a fairly new programmer and this is the first time I have encountered the problem so I have yet fully understand it and cannot seem to fix it. i have tried reading other things online, but just do not understand I would love a simple explaination to my problem.
The NPE happens because of these two lines:
PoliceOfficer po = new PoliceOfficer(pt, "Roger", 337);
System.out.println(po);
In your constructor for PoliceOfficer, you don't do anything with the ParkingTicket instance pt.
public PoliceOfficer(ParkingTicket pt /* not set anywhere */, String OfficerName, int OfficerNum) {
this.OfficerName = OfficerName;
this.OfficerNum = OfficerNum;
}
The fields ParkingMeter pm and ParkingTicket pt remain null since you haven't initialized them.
Then you try to print the object: System.out.println(po); What this does is call toString() on po, it is equivalent to this:
System.out.println(po.toString());
Now because your toString()
public String toString() {
return "Officer Name: " + OfficerName + "\nOfficer Number: " + OfficerNum + "\n" + "\nFine: " + pt.TicketCost();
}
uses the pt, it creates a NullPointerException, since pt is null.
Since you are already passing a ParkingTicket instance into the constructor for PoliceOfficer, use that instance to assign its member variable pt.
I am a student working on a project creating classes with arrays to model composition. I have assume I have everything right so far but it seem that I am getting a problem with my print statement in the driver class. I am not sure if it about the way I am method chaining the two together. Any information would be thankful.
public class MyWord
{
private String word;
public MyWord(){
word = "Null";
}
public MyWord(String s){
word = s;
}
public String getWord(){
return word;
}
public void setWord(String w){
word = w;
}
public void print(){
System.out.println(word);
}
}
public class Page
{
private MyWord[] words = new MyWord[5];
private int pageNumber;
public Page(){
MyWord words[] = {} ;
pageNumber = 0;
}
public Page(MyWord[] a, int b){
words = a;
pageNumber = b;
}
public MyWord[] getWord(){
return words;
}
public int getPageNumber(){
return pageNumber;
}
public void setMyWord(MyWord[] a){
words = a;
}
public void setPageNumber(int b){
pageNumber = b;
}
public void print(){
System.out.print(" Page Number: " + pageNumber + " " + words);
}
}
public class Book
{
private Page[] p = new Page[5];
private String title;
public Book(){
Page[] p = {};
title = " ";
}
public Book(Page[] pa, String ti){
p = pa;
title = ti;
}
public Page[] getPage(){
return p;
}
public String getTitle(){
return title;
}
public void setPage(Page[] x){
p = x;
}
public void setTitle(String y){
title = y;
}
public void print(){
System.out.print("Book info:" + p + " " + title);
}
}
public class Series
{
private Book bookOne, bookTwo, bookThree;
private double price;
public Series(){
bookOne = null;
bookTwo = null;
bookThree = null;
price = 0;
}
public Series(Book one, Book two, Book three, double p){
bookOne = one;
bookTwo = two;
bookThree = three;
price = p;
}
public Book getBookTwo(){
return bookTwo;
}
public Book getBookOne(){
return bookOne;
}
public Book getBookThree(){
return bookThree;
}
public double getPrice(){
return price;
}
public void setBookOne(Book bookOne){
this.bookOne = bookOne;
}
public void setBookTwo(Book bookTwo){
this.bookTwo = bookTwo;
}
public void setBookThree(Book bookThree){
this.bookThree = bookThree;
}
public void setPrice(double price){
this.price = price;
}
public void print(){
System.out.println("Series info");
System.out.println("Book one:" + bookOne + " Book Two: " +bookTwo
+ " Book Three: " + bookThree + "Price: " + price);
}
}
public class Driver
{
public static void main(String args[]){
MyWord[] w1 = new MyWord[2];
w1[0] = new MyWord("Hello");
w1[1] = new MyWord("Hola");
Page[] p = new Page[2];
p[0] = new Page(w1, 20);
p.print();
}
}
p is of type Page[], i.e. "array of Page". And arrays don't have a print() method. So the statement p.print() doesn't compile (you should have said that in your question, and joined the exact error message).
To print all the pages of the array, you need to loop over the array:
for (Page page : p) {
page.print();
}
Please avoid single-letter variables, and use a plural form for arrays and collections: Page[] pages = new Page[2];