Error printing out fields of geolocation object - java

import java.util.*;
public class RoadTrip
{
ArrayList<GeoLocation> roadTrip = new ArrayList<GeoLocation>();
double cheat = 0;
// Create a GeoLocation and add it to the road trip
public void addStop(String name, double latitude, double longitude)
{
GeoLocation loc = new GeoLocation(name + " ", latitude, longitude);
roadTrip.add(loc);
}
// Get the total number of stops in the trip
public int getNumberOfStops()
{
return roadTrip.size();
}
// Get the total miles of the trip
public double getTripLength()
{
double totalDistance = 0;
for (int i = 1; i < roadTrip.size(); i++ )
{
GeoLocation here = roadTrip.get(i);
GeoLocation prev = roadTrip.get(i-1);
totalDistance = totalDistance + here.distanceFrom(prev);
}
return totalDistance;
}
// Return a formatted toString of the trip
public String toString()
{
int i = 0;
String retVal="";
for( Object test: roadTrip)
{
retVal = retVal + ( i + 1 ) + ". " + test + "\n";
i++;
}
return retVal;
}
}
When I return retVal, it returns the values
Powder Springs(-110.97168, -110.97168)
Argonne(-149.00134, -149.00134)
Zeba(-84.74096, -84.74096)
Hyampom(-53.2522, -53.2522)
North Fairfield(47.05816, 47.05816)
When it should return
Powder Springs (70.47312, -110.97168)
Argonne (-12.26804, -149.00134)
Zeba (-3.89922, -84.74096)
Hyampom (84.57072, -53.2522)
North Fairfield (73.14154, 47.05816)
The problem is that the latitude value is for some reason equal to the longitude value.
EDIT: Forgot I was messing with the code and removed the latitude part, put it back in; still gives the same result

Found the error. A person working on it with me changed some code in the geolocation and didn't inform me.

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

finding the minimum value in circular array queue

public class CanadaTour {
private CircularArrayQueue<City> cityQueue;
private Map map;
private City startCity;
public CanadaTour (String fileName) {
map = new Map();
cityQueue = new CircularArrayQueue<City>();
loadData(fileName);
}
private void loadData (String file) {
MyFileReader reader = new MyFileReader(file);
reader.readString(); // First line of headers.
String cityName = null;
int locX = 0;
int locY = 0;
double earnings = 0;
int cityID = 0;
while (!reader.endOfFile()) {
cityName = reader.readString();
locX = reader.readInt();
locY = reader.readInt();
earnings = reader.readDouble();
cityID ++;
City city = new City(cityID, cityName, locX, locY, earnings);
if (cityID == 1) {
startCity = city;
}
cityQueue.enqueue(city);
map.addCity(city);
}
}
public City findNextCity (City currCity, double currMoney) {
double distance = 0;
City result = cityQueue.dequeue();
if (result != currCity || result.isMarkedInStack()
|| result.isMarkedOutOfStack()) //add other conditionals
distance = distBetweenCities(result, currCity);
cityQueue.enqueue(result);
double distance1;
for (int i = 1; i < cityQueue.getLength(); i ++) {
City result1 = cityQueue.dequeue();
if (result1 != currCity || result1.isMarkedInStack()
|| result1.isMarkedOutOfStack()) { //add other conditionals
distance1 = distBetweenCities(result1, currCity);
if (distance1 < distance) {
distance = distance1;
return result1;
}
cityQueue.enqueue(result1);
}
}
return result;
}
public double distBetweenCities (City city1, City city2) {
double result = Math.sqrt(Math.pow(city2.getX() - city1.getX(), 2) +
Math.pow(city2.getY() - city2.getY(), 2) * 1.0);
return result;
}
public double calcFlightCost (double distance) {
double flightCost;
if (distance < 100.0) {
flightCost = 127.00;
} else {
flightCost = (1.25 * distance) + 32.0;
}
return flightCost;
}
This is what I have thus far, but logically my answer seems wrong for the findNextCity method. and additionally, I don't even know how to approach the second part of the question (below).
I am supposed to go through each element in the cityQueue to determine which one is the
closest to the current city (from the first parameter) using the Euclidean distance
calculated in the next method (distBetweenCities). I must omit cities that already
marked in or out of the stack and the current city itself (otherwise a city will always be
the closest city to itself!). If the found city (with the smallest distance to current city) is
null, return null. Calculate the flight cost to this city and determine if it is affordable with
the band's current money. If so, return the city, but if it is not affordable then return null.
Without providing a complete solution, here are several pointers you might like to consider:
You seem to be dequeuing and enqueuing for the purpose of viewing the head of the queue. If your CircularArrayQueue implements Queue it should have a peek method that views the head without removing it.
The or operators in your filter condition should probably be and (&&) if I'm reading your requirements correctly
As you mention, your logic is pretty flaky in findNextCity it kinda seems to look for the first city that is smaller than the distance to the next city or something like that
You probably need something like:
City closestCity = null;
for (City testCity: cityQueue) {
if (testCity != currCity
&& !testCity.isMarkedInStack() && !testCity.isMarkedOutOfStack()
&& (closestCity == null || distance(currCity, closestCity) > distance(currCity, testCity))
closestCity == testCity;
}

Getting error while trying to implement Recursion with arrays

Im working on a school project where I have to implement recursion with arrays and I have done everything but im getting a null error when I am running it. The error points to the Recursion class on Line:
result += packetList[n].idNumber + " " + packetList[n].weight + " " + packetList[n].Destination;
I tried tracing the recursion method to see if it would actually make sense and its looks solid but i'm still getting a null error.
Recursion Class:
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;
}
}
Packet Class
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;
}
}
Test Class
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");
}
}
It looks like you are sending the length of the array to your toString() function, but it might not have the 100 elements initialized, try sending your ´counter´ instead :
System.out.println(recursion.toString(packetList, counter-1))
Please verify that packetData.txt has exactly 100 lines otherwise the program will throw a null pointer Exception.
The displayHeavyPackage method should validate if n==0 to avoid Array Index Out Bound exception
displayHeavyPackage
public void displayHeavyPackages(Packet[] packetList, int n) {
if (packetList[n].isHeavy() == true && n>0) {
System.out.println(packetList[n]); displayHeavyPackages(packetList, n-1);
} else if (packetList[n].isHeavy() == true && n==0){
System.out.println(packetList[n]);
}
}
My final suggestion is try to debug your code, it will help a lot to clarify the root cause of the exceptions.

Search in Hashmap

Using for loop to compare the input value with the hashmap if it matches any value in the hash-map then the code prints all the related values with that time.
The result shows out for me NULL
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}}
Class Measurement:
public void getTimeInfo(String value)
{
value = Measurements.get(time);
if (value == null) {
throw new MeasurementException();
}
System.out.println("The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid );
}
}
}
Following the 3 steps (ignoring the Json part) u mentioned and reusing some of your code i can provide u this code:
Main.java:
public class Main {
static HashMap<String, Measurement> measurements = new HashMap();
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {//Create 3 measurements
String time = ""+i;
measurements.put(time, new Measurement(time, (float) i, (float) i, (float) i));
}
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}
}
}
Measurement.java:
public class Measurement {
String time ;
Float temp;
Float wind;
Float humid;
int iD;
public Measurement(String d, Float t, Float w, Float h){
this.time = d;
this.temp = t;
this.wind = w;
this.humid = h;
}
#Override
public String toString() {
return "The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid;
}
}
It might not fit exactly your needs but it can be a help.

Printing out most expensive boat and it's information from an array

I am working on a boat program that has a super class (Boat) and two subclasses (SailBoat, Powerboat) and I must print out all of the boats information and price as well as the most expensive boat and it's information alone. This is the part I am having trouble with since I am not entirely sure how to go about it. Here is what I have so far...
Boat Class:
public class Boat {
String color;
int length;
public Boat() {
color = "white";
length = 20;
}
public Boat(String col, int leng) {
color = col;
length = leng;
}
public boolean setColor(String col) {
if ("white".equals(col) || "red".equals(col) || "blue".equals(col) || "yellow".equals(col)) {
col = color;
return true;
} else {
System.out.println("Error: can only be white, red, blue or yellow");
return false;
}
}
public String getColor() {
return color;
}
public boolean setLength(int leng) {
if (leng < 20 || leng > 50) {
leng = length;
System.out.println("Sail Boats can only be between 20 and 50 feet, inclusively.");
return false;
} else {
return true;
}
}
public int getLength() {
return length;
}
public String toString() {
String string;
string = String.format("Color = " + color + " Length = " + length);
return string;
}
public int calcPrice() {
int price;
price = 5000 + length;
return price;
}
}
PowerBoat Subclass
import java.text.NumberFormat;
public class PowerBoat extends Boat {
int engineSize;
public PowerBoat() {
super();
engineSize = 5;
}
public PowerBoat(String col, int len, int esize) {
this.color = col;
this.length = len;
engineSize = esize;
}
public boolean setEngineSize(int esize) {
if (esize < 5 || esize > 350) {
System.out.println(
"Error: That engine is too powerful. The engine size must be between 1 and 350, inclusively");
esize = engineSize;
return false;
} else {
return true;
}
}
public int calcPrice() {
int price;
price = 5000 + length * 300 + engineSize * 20;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + " Engine Size = " + engineSize + " Price = " + nf.format(calcPrice());
}
}
SailBoat subclass
import java.text.NumberFormat;
public class SailBoat extends Boat {
int numSails;
public SailBoat() {
numSails = 0;
}
public SailBoat(String col, int leng, int numsail) {
color = col;
length = leng;
numSails = numsail;
}
public boolean setNumSails(int nsails) {
if (nsails < 1 || nsails > 4) {
nsails = numSails;
return false;
} else {
return true;
}
} // end setNumSails
public int getNumSails() {
return numSails;
}
public int calcPrice() {
int price;
price = length * 1000 + numSails * 2000;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
}
public int getTotalCost() {
int totalCost = 0;
totalCost += calcPrice();
return totalCost;
}
}
Inventory class (tester)
import java.util.ArrayList;
public class Inventory {
public static void main(String[] args) {
// boat objects
Boat pb1 = new PowerBoat("blue", 22, 60);
Boat sb1 = new SailBoat("white", 20, 1);
Boat sb2 = new SailBoat("red", 42, 3);
Boat pb2 = new PowerBoat("yellow", 35, 80);
Boat pb3 = new PowerBoat("red", 50, 120);
Boat sb3 = new SailBoat("blue", 33, 2);
Boat pb4 = new PowerBoat("white", 20, 10);
ArrayList<Boat> AL = new ArrayList<Boat>();
// add boat objects to arraylist
AL.add(pb1);
AL.add(sb1);
AL.add(sb2);
AL.add(pb2);
AL.add(pb3);
AL.add(sb3);
AL.add(pb4);
// print all boat objects
System.out.println("Print all boats");
for (Boat anyBoat : AL) {
System.out.println(anyBoat.toString());
}
int max = 0;
int totalcost = 0;
Boat mostExpensiveBoat = null;
for (Boat anyBoat : AL) {
if (anyBoat instanceof SailBoat) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
}
}
}
I am really confused on how to finish up this program, the results I am supposed to get after all the boat information is printed is this..
Total price of all boats is $ 170,500.00
Most Expensive Boat: Color = red Length = 42 Number Sails = 3 Cost = $ 48,000.00
Any help will be greatly appreciated. Thank you.
There are a few design flaws you should correct:
Your Boat class should be an interface or abstract. You can't have a boat that isn't a power boat or sail boat so you should not be able to instantiate one.
Your instance variables should be private.
Make methods abstract that need to be defined by subclasses of Boat (e.g. calcPrice).
If you are able to use Java 8 then there's a nice way of getting the most expensive boat. The following code will print the most expensive boat (using Boat.toString) if one is present.
allBoats.stream()
.max(Comparator.comparingInt(Boat::calcPrince))
.ifPresent(System.out::println);
That avoids having to write the code that manually iterates through your list comparing prices. It also copes with the situation of an empty list (which means there is no maximum). Otherwise you need to initialise to null and compare to null before printing.
Your for loop should look like this:
for (Boat anyBoat : AL) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
It doesn't matter if it's a sailBoat or not, you just wanna print the information of the most expensive one, so you can remove the instanceof condition. After that:
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println("Total price of all boats is " + nf.format(totalcost));
System.out.println("Most expensive boat: " + mostExpensiveBoat.toString());
Should work, since you have already overriden the toString() methods.
one more thing: In your SailBoat toString() method, you are doing:
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
When you call the super.toString() you are printing the color and the length twice; just call
return super.toString() + " Number Sails = " + numSails + " Cost = " + nf.format(calcPrice());

Categories