Comparing int and String from LinkedList - java

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.

Related

Creating an ArrayList inside a recursive method

I'm attempting to solve a problem that finds the amount of valid solutions to a chess problem and when the code is printed, it prints 92 arrays of an object PartialSolution I made that are the correct solutions. This is done recursively and I need to add these arrays to an array list but I can't figure out how.
Here's my code:
public ArrayList<PartialSolution> solve(PartialSolution sol ){
ArrayList<PartialSolution> solutions = new ArrayList<PartialSolution>();
int exam = sol.examine();
if(exam == PartialSolution.accept){
solutions.add(sol);
}
else if(exam != PartialSolution.abandon){
for(PartialSolution p : sol.extend()){
solve(p);
}
}
return solutions;
}
Define a variable in class and add your lists to that list instead of print.
Or make your solve method take a second argument as list and change return type from void to list. For the the first call give it an empty list and pass that list in every recursive call. At the end return that list
If you need the ArrayList just to store the solutions for later use then you should create the list out of the method like:
static ArrayList<PartialSolution> x = new ArrayList<PartialSolution>();
then just add the solution to the list when you print sol.

Cannot invoke indexOf on an Array of strings?

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.

Method cannot access the sorted array

The following code sorts through a dictionary of words in lexicographical order. The problem is that I cannot access the sorted array outside of the for loop. Well I think this is the problem. I have declared the array words in another method and returned it to a private variable within the same class. But after I sort the array and try to print it out, it just prints out the original array. I also want to mention that this sorting method does work as I have tested it in another class where everything was in the main method. So again I believe my problem has to do with returning the new sorted array. I also need to write a few lines of code within the method after the array is sorted and when I tried to return the array, using "return words;" I was unable to write this code.
public void insertionSort() {
int in, out;
for (out=1; out<nElems; out++){
String temp = words[out]; // remove marked item
in = out; // start shifting at out
while (in>0 && words[in-1].compareTo(temp)>0){ // until temp is lexicographically after after the word it is being compared to
words[in] = words[in-1]; // shifts word to next position in lexicographical order
--in;
}
words[in] = temp;
}
for(int i=0; i <words.length; i++)
System.out.println(words[i]);
I have declared the array words in another method
It sounds like you have declared two arrays: one inside the other method and an entirely separate one at class level that is being sorted. Make sure both methods are using the same array.
If you want them both to use the array declared at class level, don't declare a separate array in the other method. E.g., if you have String[] words = new String[10]; in the other method, change it to words = new String[10];. If you really need the nElems variable (i.e., if the sort method can't simply use words.length), make sure that variable is also not being redeclared and is being set to the correct value.
Alternatively, instead of depending on putting the data to be sorted in a particular array, your sort method would be more generally useful if it accepted any array to be sorted as a parameter:
public static void insertionSort(String[] words, int nElems) {
/* ... rest of method as before ... */
}
I've made that method static too, since it no longer depends on any instance fields.
Well, as I understand what you are saying, you are using a private variable at class level and that variable receives the words[] array items from a method... in that case:
Make sure the private variable at class level is an array named words.
Make the private variable (now named words) the same type as the words array received from the other method.
Because you are calling words from insertionSort() you need to acces the private variable values, you can't get the words[] array values from the other method, because that array is local to that method, so you must return it's values to some array varibale (the private variable that you must name words), so it's that variable that you must access.

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'

How to retrieve objects values stored in a Java ArrayList

ArrayList<yellowPage> ob1 = new ArrayList<yellowPage>();
yellowPage thing = new yellowPage(100,100);
thing.calc(i,y,s3);
ob1.add(thing);
I stored some data in thing. How can I retrieve the value stored in ob1.thing?
If you know the index, you can do yellowPage
yellowPage yp = ob1.get(index);
Otherwise you need to iterate over the list.
Iterator<yellowPate> iter = ob1.iterator();
while(iter.hasNext())
{
yellowPage yp = iter.next();
yp.whateverYouwantGet();
}
Note: I just typed code here, there may be syntax errors.
int x=5;
int info=ob1.get(x).getInfo();
The above example will get whatever information you wanted from your yellow pages class (by using a getter method) at the 6th index (because 0 counts) of your array list ob1. This example assumes you want an integer from the yellow page. You will have to create a getter method and change the x to the index of the yellow page you want to retrieve information from.
An example getter method (which you should put in your yellow pages class) could look like this:
public int getInfo() { return z; }
In the above case z may be an instance variable in your yellow pages class, containing the information you're looking for. You will most probably have to change this to suit your own situation.
If you wanted to get information from all yellow pages stored in the array list then you will need to iterate through it as Chrandra Sekhar suggested
Use an Iterator object to do this.
ArrayList<yellowPage> ob1 = new ArrayList<yellowPage>();
yellowPage thing = new yellowPage(100,100);
thing.calc(i,y,s3);
ob1.add(thing);
yelloPage retrievedThing = null;
Iterator<yelloPage> i = ob1.iterator();
if(i.hasNext()){
retrievedThing = i.next();
}
You could have the data stored in thing (horribly named variable) simply returned from the calc method. That way you don't need to maintain state for prior calculations in subsequent calls. Otherwise you just need a getter type method on the YellowPage class.
public class YellowPage {
private int result;
public void calc(...) {
result = ...
}
public int getResult() {
return result;
}
}
Print the list and override toString method.
public String toString()
{
return (""+ a+b); //Here a and b are int fields declared in class
}
System.out.print(ob1);
Class ArrayList<E>
Syntax
ArrayList<Integer> list = new ArrayList<Integer>();
You replace "Integer" with the class that the list is of.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
E represents an Element, which could be any class.
ensureCapacity is used to ensure that the list has enough capacity to take in the new elements. It's called internally every time you add a new item to the list. As the name suggests, ArrayList uses an Array to store the items. So when the array is initialized, it's given an arbitrary length, say 10. Now once you've added 10 items, if you go to add the 11th item, it'll crash because it exceeds the arrays capacity. Hence, ensureCapacity is called (internally) to ensure that there's enough space. So if you were adding the 11th element, the array size might be, say, doubled, to 20.

Categories

Resources