My code :-
public static void main(String[] args) {
//Scanner object.
Scanner scanner = new Scanner(System.in);
//Creating ArrayList.
ArrayList<Integer> list = new ArrayList<>();
//Creating index varibale to use as counter and keep track of inputs.
int index = list.size() - 1;
//Creating a loop to add user inputs in the list.
while(true) {
//Ask for user input.
int user_input = Integer.valueOf(scanner.nextLine());
if(user_input == -1) {
break;
} else {
list.add(user_input);
index ;
}
}
while(true) {
//Asking the user for what number to search for in the elemnets.
//Search for it in list and show its index as output.
System.out.print("Search for ");
int ask_user = Integer.valueOf(scanner.nextLine());
if(list.get(index) != ask_user) {
index ;
continue;
} else {
System.out.println(ask_user " is at index " index);
break;
}
}
}
Now whenever the userinput is like this :-
4
5
6
7
9
10
-1
Search for 10
Output :- 10 is at index 6
Sample input 2 :-
3
4
5
6
7
Search for 7
Output :- 7 is at index 4
This is running fine, but the problem arises when I type inputs like this.
Sample input 3 :-
33
22
55
-1
Search for 22
Search for 33
Output :- Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.get(ArrayList.java:435)
at IndexOf.main(IndexOf.java:40)
or
Sample input 4 :-
33
18
-127
90
-345
9
7
37
-1
Search for 9
Search for 9
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 8
at java.util.ArrayList.rangeCheck(ArrayList.java:659)
at java.util.ArrayList.get(ArrayList.java:435)
at IndexOf.main(IndexOf.java:40)
What is going on?
I don't know what am I doing wrong, maybe it has something to do with storage, maybe int is not enough or something.
Help please.
CodePudding user response:
Your index is not reset between your two loops, so the second loop will check the last element, then an element with one higher index than the last which does not exist, and throw an exception.
You are also asking for input on every iteration of the second loop, presumably the desired behaviour is to search the entire list for each input. I recommend looking into for-each loops for this to avoid the index issue altogether.
CodePudding user response:
"int index = list.size() - 1" will effectively make the index as -1 at the beginning and thus will always be 1 less than what it's supposed to be, also I think instead of using the variable index, just use size()-1 in your program