I have two arrays of double values called lat2[] and lon2[]. I have there stored the particular lattitude and longtitude values. And I can get those values as simple double values. My question is how can I find if this two doubles exist in the array (to check which marker has been clicked simply). Here is what I've done so far but it doesnt seem to work:
#Override
public boolean onMarkerClick(Marker marker) {
markerLatLng = marker.getPosition();
markerLat = markerLatLng.latitude;
markerLng = markerLatLng.longitude;
for (int i = 0; i < lat2.length; i++) {
if (markerLat == lon2[i]) {
for (int j = 0; j < lon2.length; j++) {
if (markerLng == lon2[j]) {
String title = marker.getTitle();
Log.e("TAG", " " + title);
}
}
}
}
return true;
}
Probably if I understood your data structure there is a problem in your for loop.
If you store latitude and longitude in two arrays I imagine that a point in position n is defined by longitude[n] and latitude[n].
If this is how you store your points here is how you need to update your code:
#Override
public boolean onMarkerClick(Marker marker) {
int markerLat = marker.getPosition().latitude;
int markerLng = marker.getPosition().longitude;
for (int i = 0; i < lat2.length; i++) {
if (markerLat == lat2[i] && markerLng == lon2[j]) {
String title = marker.getTitle();
Log.e("TAG", " " + title);
}
}
return true;
}
Please don't use global variables. I edited your code to define markerLat and markerLng local to the method (I don't know if int is the correct type).
Create a List for example ArrayList from the lat2, log2 array and check if the numbers contains like:
List lat = new ArrayList(lat2);
List lon = new ArrayList(lon2);
if (lat.contains(markerLat) && lon.contains(markerLng)){
String title = marker.getTitle();
Log.e("TAG", " " + title);
}
Related
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;
}
I'm writing a simple script in Java that is calling another class that holds all my information.
I am holding my information in the called class in Object[] Arrays and I am planning on calling the script to fetch that array.
Right now the function looks like this.
public void tradeShop() {
/*
*Variables must be initialized in order to call shopTrader
*The values are just non-null placeholders and they are
*replaced with the same values in the tradeValues Object array.
*/
String targetName = "NPC Name";
String itemName = "Item Name";
int itemQuantity = 1;
int minCoins = 1;
int minBuy = 1;
boolean stackable = false;
Object[] tradeValues = shop.defaultValues;
for (int i = 0; i < tradeValues.length; i++) {
if(String.class.isInstance(tradeValues[i])) {//String check
if(i==0) { //0 is NPC Name
targetName = (String) tradeValues[i];
} else if (i==1) { //1 is Item Name
itemName = (String) tradeValues[i];
}
} else if (Integer.class.isInstance(tradeValues[i])) { //Int check
if(i==2) { //2 is Item Quantity
itemQuantity = (Integer) tradeValues[i];
} else if (i==3) { //3 is Minimum coins
minCoins = (Integer) tradeValues[i];
} else if (i==4) { //4 is the Minimum Buy limit
minBuy = (Integer) tradeValues[i];
}
} else if (Boolean.class.isInstance(tradeValues[i])) { //Bool check
stackable = (Boolean) tradeValues[i]; //5 is the item Stackable
} else {
//TODO: Implement exception
}
}
//Calls ShopTrader() method shopTrader
ShopTrader trade = new ShopTrader();
trade.shopTrader(targetName, itemName, itemQuantity, minCoins, minBuy, worldHop, stackable);
}
I feel like using a for loop like this is not the correct way for me to be looping through these Objects, I shouldn't have to check i== for each variable.
Also it hinders me from adding overloads to the shopTrader method as I would have to write an entirely new for loop for each overload.
Does anyone have a more elegant solution for getting the variables from this array?
I think that instead of storing all of your information in Object[], you may want to create a new class to act as a data structure i.e.
public class TradeValue {
String targetName;
int itemQuantity;
// etc.
String getTargetName() {
return targetName;
}
String getItemQuantity() {
return itemQuantity;
}
// etc
}
You can then just access the information directly
TradeValue defaultValues = shop.defaultValues;
String targetName = defaultValues.getTargetName();
int itemQuantity = defaultValues. getItemQuantity();
...
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.
I spent several hours working on this and even had my professor look at this and it seems to be printing out just the last element in the for loop. It seems to allows me to add the data structure information and initialize the array queue but it only print out the last element. Here is the sufficient code to assist with the question.
static int MAX;
static final int amount = 6;
static boolean [] openflag;
static queue [] Clinic;
static String [] Doctor;
final static String HEADING = "The clinic moniter of Dylan Rychlik";
public static void Listpaitents( ) {
Paitent[] array;
int queuechoice;
JOptionPane.showMessageDialog(null, "Which doctor would you like to
print?");
String InputString = JOptionPane.showInputDialog(null,Doctor, HEADING,
JOptionPane.QUESTION_MESSAGE);
queuechoice = Integer.parseInt(InputString);
if (openflag[queuechoice -1 ] == false){
JOptionPane.showMessageDialog(null, "Sorry, that doctor is not aviable");
}
else {
//Paitent[] array = null;
int limit;
limit = Clinic[queuechoice -1 ].getSize();
array = Clinic[queuechoice -1 ].toArray();
System.out.println(array[0]);
System.out.println(array[1].Print());
System.out.println(array[2].Print());
//int size = Clinic[queuechoice -1].getSize();
//System.out.println(limit);
int x; String out = " Members of the list are: \n";
// boolean exit = false;
for(x = 0; x < limit; x++) {
out += array[x].Print() + "\n";
//System.out.println(out);
// System.out.println(Clinic[queuechoice].toString() + "\n");
}
System.out.println(limit);
JOptionPane.showMessageDialog(null,out);
}
}
Here this is the array() method in the queue clas
public Paitent[] toArray() {
int x;
Paitent[] Array = new Paitent[Length];
queuenode Current = rear;
for (x = 1; ((Current != null) && (x <= Length));x++) {
Array[x-1] = new Paitent();
Array[x-1].update(Current.info);
Current = Current.next;
// System.out.println( Array[x-1].Print());
}
//System.out.println( Array[x-1].Print());
return Array;
}
Any finally here this is the print method
public String Print() {
String outputString;
outputString = "Paitent: " + "-" + name + "\n" + " Telephone number
telephone + " ID " + ID;
return outputString;
}
Any help you can give is really appreciated. I really have spent hours analyzing the code to come up a solution. Its a bulky program.
how can i scroll a view (recyclerview) in relation to my tts,
ive looked at onUtterance but it seems to only have a start and stop listener, so i need to think outside the box, i give my tts a string from an Arraylist like this
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++)
{
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
speakWords(words);
I was thinking about cutting the string up into sections and giving it to the TTS one string at a time and move the view as I go. I already give my gridlayout manager an int for the amount of columns (called columns).
The array list adds a comma after every word, so I was thinking something like
find the nth/(column) comma
split the string
check if tts is speaking and listen for onUtterance onDone to pass new string
read the string
move the view
and keep doing this until theres no words left and coding for the remainder % im not sure how to do all of that so if anyone wants to help feel free, (I think Im looking at StringUtils and creating each smaller string with a for loop and passing them to the tts in onUtteranceListener onDone, but im still a little new to android), but mainly does anyone have a better way
okay this is what i have so far but it could probably use some work im still an amateur, I've split the string into blocks based on the size of the screen, and the handler that scrolls the screen relies on the amount of letters in each broken up string, also the smoothscrolltoposition is scrolling a custom layout manager that scrolls pretty slowly im having an issue though where on some devices the array list counting the words will only reach 20 not sure why but ill ask and hopefully update this when ive fixed it so here is my speak and move method
public void speakAndMove(){
final ArrayList<String> list = new ArrayList<>();
SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(0);
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++) {
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
Integer numOfWords = list.size();
words = list.toString();
Integer count = 0;
Integer startPoint = 0;
scrollPos = 0;
final Integer speed = words.length() * 15;
Integer leftOver = 0;
final int columns = getResources().getInteger(R.integer.grid_columns);
System.out.println(numOfWords);
ArrayList<String> arrayList = new ArrayList<>();
if (list.size() <= columns) {
if (words.contains("[]")) {
speakWords("");
} else if (words.contains(", 's")) {
formatString = words.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (words.contains(", ing")) {
formatString = words.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(words);
}
}
if (list.size()>=columns) {
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) == ',') {
count++;
if (count == columns) {
String ab = words.substring(startPoint, i + 1);
//speakWords(ab);
if (ab.contains(", 's")) {
formatString = ab.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab.contains(", ing")) {
formatString = ab.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab);
}
startPoint = i + 1;
count = 0;
leftOver = words.length() - startPoint;
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("main string"+" scroll " + scrollPos + " startpoint " + startPoint +" speed " + speed);
}
}
if (leftOver > 0) {
String ab2 = words.substring(startPoint, words.length());
//speakWords(ab2);
if (ab2.contains(", 's")) {
formatString = ab2.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab2.contains(", ing")) {
formatString = ab2.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab2);
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("leftovers "+ leftOver + " scroll " + scrollPos + " startpoint " + startPoint +" count " + scrollPos);
count = 0;
//scrollPos = 0;
}
}
final Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
scrollPos = scrollPos + columns;
SpeakGrid.recyclerView.getLayoutManager().smoothScrollToPosition(SpeakGrid.recyclerView, null ,scrollPos);
System.out.println("position "+ scrollPos + " speed " + speed + " list size " + list.size());
if (scrollPos < list.size())
h.postDelayed(this,speed);
// close this activity
}
}, speed);
}