You have ArrayList all wrong,
- You can't have an integer array and assign a string value.
- You cannot do a
add()method in an array
Rather do this:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0 to N-1 where N is size() of list.
You have ArrayList all wrong,
- You can't have an integer array and assign a string value.
- You cannot do a
add()method in an array
Rather do this:
List<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");
String value = alist.get(1); //returns the 2nd item from list, in this case "banana"
Indexing is counted from 0 to N-1 where N is size() of list.
Read more about Array and ArrayList
List<String> aList = new ArrayList<String>();
aList.add("apple");
aList.add("banana");
aList.add("orange");
String result = alist.get(1); //this will retrieve banana
Note: Index starts from 0 i.e. Zero
- Resource
Java while loop to find index of elements in ArrayList
How to get current index of ArrayList?
Why is .remove(index) of ArrayList not working?
Java Array list with more than 2^31 items?
Videos
I'm sorry for the possibly bad title! Didn't know what else to put there.
So my problem is, I am doing the MOOC course for java from University of Helsinki, and my challenge was to create a program which reads input from user and puts it on an ArrayList. If the user enters -1, the reading will end. After the list has been created (user enters -1), the program will ask the user for number and print out all the indexes where that number exists in the ArrayList. I have blasted my way through all of the earlier challenges but just can't manage to wrap my head around this. I do know how to solve this with for-loop and arrays, but I'm supposed to solve it using a while loop and without the use of arrays.
My current code is this:
if(list.contains(number)) {
while(i < list.size()) {
spot = list.indexOf(number);
i++;
}
System.out.println("Number " + number + " is in the index " + spot);
} and it works just fine when I have a list that contains only 1 instance of a number. But when I have a list that has for example two times the number eight in different indexes, it will only return the first one. Any suggestions?