Cannot invoke indexOf on an Array of strings? - java

I'm writing a method to calculate the distance between 2 towns in a given array by adding all the entries between the indexes of the two towns in the second array, but I can't invoke indexOf on the first array to determine where the addition should start. Eclipse is giving me the error "Cannot invoke indexOf on array type String[]" which seems pretty straight forward, but I do not understand why that won't work.
Please note the program is definitely not complete.
public class Exercise_3 {
public static void main(String[] args){
//Sets the array
String [] towns={"Halifax","Enfield","Elmsdale","Truro","Springfield","Sackville","Moncton"};
int[] distances={25,5,75,40,145,55,0};
distance(towns, distances, "Enfield","Truro");
}
public static int distance(String[] towns,int[] distances, String word1, String word2){
int distance=0;
//Loop checks to see if the towns are in the array
for(int i=0; i<towns.length; i++){
if(word1!=towns[i] || word2!=towns[i] ){
distance=-1;
}
//Loop is executed if the towns are in the array, this loop should return the distance
else{
for(int j=0; j<towns.length; j++){
*int distance1=towns.indexOf(word1);*
}
}
}
return distance;
}
}

No, arrays do not have any methods you can invoke. If you want to find the index of an given element, you can replace String[] by ArrayList<String>, which has an indexOf method to find elements.

It doesn't work because Java is not JavaScript.
The latter offers an array prototype that actually exposes the function indexOf, while the former does not.
Arrays in JavaScript are completely different from their counterparts in Java.
Anyway, you can be interested in the ArrayList class in Java (see here for further details) that is more similar to what you are looking for.

How about this (from this post)?
There are a couple of ways to accomplish this using the Arrays utility class.
If the array is not sorted:
java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search for performance:
java.util.Arrays.binarySearch(theArray, o)
I hope this helps you. If it doesn't, please downvote.

Related

C# Multidimensional Arrays vs Java Multidimensional Array

I'm relatively new to C# and the way it handles multidimensional arrays compared to Java is screwing with me.
I'm sure there's a simple solution and that I'm gonna feel really stupid for not realizing it, but I can't seem to find an answer online or figure it out myself.
Consider the following code snippet in java:
Object firstElement(Object[] arr) {
return arr[0];
}
This would return the first element of an array of any number of dimensions; however, in C# this will throw out an error for greater than one dimension because it doesn't recognize a multidimensional array as an object array. The only way to do this I found was by casting the multidimensional array to a System.Array and then using the following code:
object firstElement(Array arr) {
foreach (object obj in arr)
return obj;
}
Is it even possible to do this without a foreach loop in the function? I have tried returning the object using arr.GetValue(0) but this will throw an error again if the array is not one dimensional. Thanks for helping this C# newbie out!
C# expects you to address every dimension in a multidimensional array even if you are meaning to access, say, [0,0].
Object firstElement(Object[] arr) {
return arr[0];
}
For this reason, the code above will throw at compile time.
this code only takes one-dimensional arrays. Try this instead:
Object firstElement(Object[][] arr) {
return arr[0][0];
}
Adjust amount of brackets according to the amount of dimensions.
It is also more common to use the keyword-aliases for primitives like object or int. I do suspect you will replace the Object with an actual class / struct instance or primitive at some point.
object firstElement(object[][] arr) {
return arr[0][0];
}
What I would suggest you reading up on are the two different types of "multidimensional"-arrays: Jagged and actual multidimensional-arrays. The key difference is that each row has to have the same amount of columns in a multidimensional-array whereas the jagged array can be irregular in this regard.
/edit:
I seem have to misunderstood your intention. I believe you try to get every first element of each row. If that is the case then try this one:
List<object> firstElements(object[][] arr)
{
List<object> firsts = new List<object>();
for(int i = 0; i < arr.length; i++)
{
firsts.Add(arr[i][0]);
}
return firsts;
}

Descending Selection Sort

I have wrote a selection sort method to descend the numbers of the array. The header of the method is:
public static void selectionSort(int[] num) { ... }
In the main class, I prompted the user to enter he size of the array and the numbers inside the array, but I ran into compiler error that it didn't except how I wrote the method with the array in the main class.
int sorted = selectionSort(arrayNum[arraySize]);
System.out.println("Sorted numbers of the array are: " + sorted);
I know there is a problem because of the int sorted isn't the same with the array int[] arrayNum, and there is a problem with my usage of the method.
What is the correct way to write the array of the main class in that method?
The working code in this online compiler ide.
The basic issue is, the selection sort implantation you probably implemented or took from book is implanted in a typical way where the the sort method modifes the input array.
So just pass the array, the array will not contain the sorted elements.
Note: in the example, I have just used the existing sorting method that sorts ascending order. Fix that method with your implementation.
int[] num = { 4, 8,2,1,6};
selectionSort(num);
System.out.println(Arrays.toString(num));
https://www.codiva.io/p/be4128fd-3a65-4b1a-8bb0-721fa5107369

Is there a way to use the compareTo() method for a data set, without iterating through each element of the set?

I am wondering if there is a way to use compareTo() without having to iterate through each string element in the data set, I'm pretty sure this is not possible using arrays, but is there a data structure that is capable of working in that way?
See example below for clearer explanation:
public static int PronounDetector(String [] pronouns)
{
String [] you = {"you", "You"};
for (int i = 0; i < pronouns.length; i++)
{
if (pronouns[i].compareTo(you) == 0)
//Is there a way for compareTo to run through
//the entire String data set without having to make
//it iterate through each element using a for loop?
{
return 2;
}
}
}
EDIT: I understand that no matter what the program will iterate through the data set, (how else will it find a match?), I am just looking to see if there is a way to do it without me actually having the physically type in the for loop.
The must be meet two conditions if you want to skip some data during search processing.
The data must be related.
The data must be organized.
You can improve your search, by sorting the array and then compare from the middle.
Then in each step you will reduce element that must be compare by half.
Instead of array you can used TreeMap, that will store the data in tree structure to have same result.
Code example:
public static boolean contains(String[] array, String key) {
Objects.requireNonNull(array,"The array must not be null");
Objects.requireNonNull(array,"The key must not be null");
String[] copy = array.clone();
Arrays.sort(copy);
return Arrays.binarySearch(copy, key) != -1;
}
Yes, you don't have to "double iterate" (even though that's exactly what happens under the hood) you can convert the array you to a string and search it using contains():
String youStr = Arrays.deepToString(you);
System.out.println(youStr.contains(pronouns[0])); // prints 'true'

array-element:array-name in Java

Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?
public class foreachloop {
public static void main (String [] args) {
int [] smallprimes= new int [3];
smallprimes[0]=2;
smallprimes[1]=3;
smallprimes[2]=5;
// for each loop
for (int element:smallprimes) {
System.out.println("smallprimes="+element);
}
}
}
It's another way to say: for each element in the array smallprimes.
It's equivalent to
for (int i=0; i< smallprimes.length; i++)
{
int element=smallprimes[i];
System.out.println("smallprimes="+element);
}
This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.
See the Java Tutorial for details.
for(declaration : expression)
The two pieces of the for statement are:
declaration The newly declared block variable, of a type compatible with
the elements of the array you are accessing. This variable will be available
within the for block, and its value will be the same as the current array
element.
expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array. The
array can be any type: primitives, objects, even arrays of arrays.
That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.
The i variable is updated at the beginning of each iteration with a value from the array.
Since there are not constructors in your code snippet it seems you are confused with terminology.
There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.
The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.

Comparing int and String from LinkedList

I've got a problem.
I'm trying to compare a String and a int but can't seem to get working.
What am I doing wrong?
Getting this from Eclipse:
The type of the expression must be an array type but it resolved to List
int numberOfMoves;
List<String> highscoreLinkedList = new LinkedList<String>();
if (moves < Integer.parseInt(highscoreLinkedList[2])){
highscoreLinkedList[2] = Integer.toString(moves);
highscoreLinkedList[1] = name;
}
This is for a highscore textfile for a game I'm making. The String at index 2 is a number of moves and the int moves is also a number of moves.
You cannot access a list element using highscoreLinkedList[2] - that syntax is reserved for arrays. To access a list you have to use the get() method, i.e. highscoreLinkedList.get(2)
You are trying to treat list as an array, but the only way to access elements of the is through calling get() method. Your code does not compile.
Lists don't work the same way as arrays in Java. To access a certain element, you have to use the get() method, and to get the element, you need to use set(), like so:
// you have highscoreLinkedList[2], it should be:
highscoreLinkedList.get(2);
// you have highscoreLinkedList[2] = ..., it should be:
highscoreLinkedList.set(2, Integer.toString(moves));
You can see all of the methods for LinkedList here.

Categories

Resources