How to loop through an array to find the closest distance? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm stuck trying to figure out how to loop through an array of zip codes and find the closest zip code to a target. The zip codes also contain their latitude and longitude which is used to calculate the distance to the target. I need figure out how to loop through the array storing the closest distance and then returning the zip code of the closest one. Any help would be great because I've tried everything I can think of.
* Finds and returns the zip code of a postal zone in the collection
* whose centroid is closest to a given location.
*
* #param target the target location.
*
* #return returns zipCode of the postal zone whose centroid is closest;
* returns COLLECTION_EMPTY if no zones are in the collection.
*/
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation()
.calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i]
.getZoneLocation().calcDistance(target);
counter++;
return closeZip;
}
}
return closeZip;
}

According to doc:
A method returns to the code that invoked it when it
1. completes all the statements in the method,
2. reaches a return statement, or
3. throws an exception,
whichever occurs first.
It means that your code finishes its work after the first iteration. As far as I understand you want to find the closest one among array of zones.
I guess you don't need return inside loop. Please comment or delete it .
public String findClosestZone(Location target)
{
int counter = 0;
String closeZip = COLLECTION_EMPTY;
double closestDistance = 100.0;
for (int i = 0; i < this.zoneCount; i++)
{
if (this.zones[i].getZoneLocation().calcDistance(target) < closestDistance)
{
closeZip = this.zones[i].getZoneZipCode();
closestDistance = this.zones[i].getZoneLocation().calcDistance(target);
counter++;
// return closeZip;
}
}
return closeZip;
}

Related

Absolutely dead confused about what is going in this code and problem. Can someone explain to me where to even begin? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I have to apply linear scan to this problem, and I just don't even know where to start. I feel as if I should change my career path honestly, this is a simple intro problem and i'm just not understanding anything about it.
/**
* Applies the linear scan strategy to counting the number of negative
* values in an array.
*/
public class CountNegatives {
/**
* Returns the number of negative values in the given array.
*/
public static int countNegatives(int[]a) {
neg=0;
for{i=0;i<a.length;i++}
if(i>0)
neg = neg+1;
return neg;
}
}
I've tried running this in VS and a tool my school uses called JGrasp. Both told me the { should be ( , the ; between length and i should be > , i<a.length is not a statement, and that } should be ;
When I change any of these things, it tells me variable neg=0 cannot be found and doubles the amount of errors in the code.
There are a few things you missed,
You did not initialize the neg=0; value with the proper data type; you should initialize it with the proper data type, which int his case is int, correct initialization would be int neg = 0;
the other problem would be in the for loop you still need to initialize i with a data type
the if statement is wrong, it should be 'i<0' instead cause with your code you are just counting the positive values
You are comparing the index value with 0 so you won't get the right value, instead, you should compare the value in the array that corresponds to that index, you can do this by arrayName[index].
The correct code would be as follows:
static int countNegatives(int[] a) {
int neg = 0;
for(int i = 0; i < a.length; i++) {
if(a[i] < 0) neg++;
// this will just work as neg = neg +1;
}
return neg;
}
}
public class CountNegatives {
/**
* Returns the number of negative values in the given array.
*/
public static int countNegatives(int[]a) {
int neg=0;
for(int number : a){
if(number<0) {
neg=neg+1;
}
}
return neg;
}
}

Keeping a running average of values in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
I am trying to calculate the average of values given via repeated function calls.
Actually Bluej allows me to put the number to rate but if i am trying to put again it replaces the previous one, i want to be stored and after that an average to be shown.
I can't figure out how to do it
This is the part of code:
public int getRate() // here i put an int number
{
return this.rate;
}
public void setRate(int rate) // here i change it but i think i don't need it
{
this.rate = rate;
}
I can't use strange or complex commands because i am allowed to only use this type of commands like get/set and arraylists.
It is a school assignment.
Thanks
An easy way to keep an average of inputs is to keep track of:
The sum of all inputs received so far.
The number of inputs you have received.
Every time you call setRate to update the rate, you add to the sum and increment the count. You also need a special case for when no rates have been added yet, to avoid division by zero:
private int ratesSum = 0;
private int rateCount = 0;
public int getRate()
{
return this.rate;
}
public void setRate(int rate)
{
this.rate = rate;
this.ratesSum += rate;
this.rateCount++;
}
// Gets the average of all rates so far, or returns zero if no rates
// have been set yet.
public float getAverageRate()
{
// Do not divide by zero
if (rateCount == 0) return 0;
return ((float)ratesSum) / ((float)rateCount);
}

Homework: Magic Plant Recursion Exercise in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
To make it clear, this IS a graded assignment for my Programming II class. I've generally been very easily receptive to new programming concepts but this particular assignment on recursion is really throwing me and I'm looking for some good nudging in the right direction. Below is the assignment verbatim and the code I currently already have.
Magic Plant
We have a magic plant that once it is planted, it germinates and grows two leaves in the first year. It doubles its leaves every year except that every three years it triples its leaves. Something like:
Write a class called MagicPlant that includes the following methods:
A method that returns the number of leaves given the age of the plant
A non-recursive method that returns the age of the plant given the number of leaves.
A recursive method that returns the age of the plant given the number of leaves.
In a driver class test the methods.
Find out what is the largest (oldest) plant that your algorithm and data structure can handle.
That is what I was given and I'm having trouble on the last bullet point as well as a bit muddy on the second one (but I have code that seems to work).
My current code excluding the Driver class since it's just call statements:
public class MagicPlant {
// Method that returns the number of leaves given
// the age of the plant.
public int getLeaves(int age) {
int leafCount = 1;
for (int i = 1; i <= age; i++) {
if (i % 3 != 0) {
leafCount *= 2;
} else {
leafCount *= 3;
}
}
return leafCount;
}
// Non-recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeNR(int leaves) {
int age = 1;
while (leaves > getLeaves(age)) {
age++;
}
return age;
}
// Recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeR(int leaves) {
return 0;
}
}
My tipp is, to replace the while-loop with recursion. So you don't have a local variable but instead give that variable back into the method (recursive).
Also i would suggest that you make 2 methods for the recursion:
public int getAgeR(int leaves){
return getAgeR(1, leaves); // call overload with initial value
}
private int getAgeR(int age, int leaves){
// do your magic here
}
// Recursive method that returns the age of the plant
// given the number of leaves.
public int getAgeR(int leaves) {
if(leaves == 2) {
return 1;
}
if(leaves % 3 == 0) {
return getAgeR(leaves/3)+1;
} else {
return getAgeR(leaves/2)+1;
}
}
It's the inverse of counting years. Instead of starting from the beginning, you just have to start from the end and decreasing for every recurrent loop.

Printing "*" with recursion [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I would need some help to solve one exercise. In this method I have to print the number of asterisks ("*") that are equal of 2 of power of x.
For example, if I have 2 of power of 2 it should print 4 asterisks ("****");
I have a method that returns me the right number, but I have problems using that number for printing those asterisks.
Here is my code:
public static int writeStars(int number) {
if (number == 0) {
return 1;
} else {
int number2 = 2 * writeStars(number - 1);
System.out.println(" number " + number2);
return number2;
}
}
Here's one idea for solving the problem, without giving away the solution in code.
Your thoughts are on the right track, realizing that 2x = 2 * 2x-1. To print 2x * characters, you can print 2x-1 twice. In your recursive method, have your base case print one * character, and have your recursive case make the recursive call twice, passing the appropriately adjusted value.
One way to do it is to create a string of 2^(i-1) stars at the i-th iteration. So, for 4 iterations (x=4), you will have 8,4,2,1 stars for each iteration. You can return the string of stars for each iteration and concatenate them to get the final string.
The terminating condition will be when the input size is 0. This code might help:
public static String writeStars(int y) {
//y is 2^x
if( y == 0)
return "";
int num_stars = y - y/2;
StringBuffer stars_Buffer = new StringBuffer(num_stars);
for (int i = 0; i < num_stars; i++){
stars_Buffer.append("");
}
return stars_Buffer.toString() + writeStars(y/2);
}
Call writeStars with input 2^x:
writeStars(Math.pow(2, x));
Because it is a return method in your client you should have
int num = writeStars(someNum);
Then to print, you just need a simple for loop
for(int i=0; i < num; i++)
System.out.print("*");

Java "Reached end of file while parsing" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm not exactly new to programming, but for some reason I cannot get past this issue. I'm writing a method, and keep getting the "reached end of file while parsing" compiler error. Normally this happens when you forget a }, but this method only has two sets of brackets, and I'm not missing either close. Could anyone point out why I'm getting this error?
public class Locations{
//member variables
static int totalNumberOfRooms = 0;
int numberOfExits;
//pointers to each exit
String roomGeneralDescription;
String roomDescription;
//member methods
String getRoomGeneralDescription(){
return this.roomGeneralDescription;
}
String getRoomDescription(){
return this.roomDescription;
}
//constructor to more easily create objects
public Locations(int exit, String description, String generalDescription){
totalNumberOfRooms += 1;
numberOfExits = exit;
roomDescription = description;
roomGeneralDescription = generalDescription;
}
//default constuctor
public Locations(){
totalNumberOfRooms += 1;
}
//generates the given number of Locations obejcts, with pointers stored in a returned
//array.
Locations[] createLocations(int x){
int iterate = 1;
int loopMax = x;
Locations[] arrayOfLocations = new Locations[x -1];
while (iterate <= loopMax){
int index = iterate -1;
arrayOfLocations[index] = new Locations();
iterate += 1;
}
return arrayOfLocations;
}
You are missing a closing brace } at the end of your file.
Locations[] createLocations(int x){
int iterate = 1;
int loopMax = x;
Locations[] arrayOfLocations = new Locations[x -1];
while (iterate <= loopMax){
int index = iterate -1;
arrayOfLocations[index] = new Locations();
iterate += 1;
}
return arrayOfLocations;
}
} // YOU NEED TO ADD A CLOSING BRACE TO FINALIZE THE CLASS DEFINITION
Update: Even though the closing brace was the solution, I couldn't help but notice at how your createLocations method is actually written. It's an odd way to do an array allocation. I'm not even sure what you have will run without crashing because the array is allocated to be of size [x-1]. In any case, here's a more clean solution to creating an array in Java. I hope this helps!
Locations [] createLocations(int count) {
Locations [] arrayOfLocations = new Locations[count];
for (int i = 0; i < count; i++) {
arrayOfLocations[i] = new Locations();
}
return arrayOfLocations;
}
} // YOU NEED TO ADD A CLOSING BRACE TO FINALIZE THE CLASS DEFINITION

Categories