Below is the code that I wrote:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
for(int a=0,i=0;list.get(i)!=42;i++){
a=sc.nextInt();
list.add(i,a);
}
for(int i=0;i<list.size();i++){
out.println(list.get(i));
}
}
}
And this is the error im getting:
Execution failed. java.lang.IndexOutOfBoundsException : Index: 0, Size: 0
Stack Trace: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:653) at java.util.ArrayList.get(ArrayList.java:429) at Uni.main(Uni.java:8)
Can you please help with what to do?
James Wong
4,6494 gold badges52 silver badges69 bronze badges
asked Jun 24, 2018 at 16:12
1 Answer 1
Maybe you wanted to use a while cycle? It's much easier to initialize the list.
Furthermore, your code is checking if list.get(i)
is not equal to 42, but you cannot do that because your list at the index 0 is still null.
A solution could be:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0;
while(i!=42) {
list.add(i++,sc.nextInt());
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}
EDIT: to stop after the Input is 42:
import static java.lang.System.out;
import java.util.Scanner;
import java.util.ArrayList;
class Uni{
static public void main(String...args){
Scanner sc = new Scanner(System.in);
ArrayList<Integer>list = new ArrayList<Integer>();
int i = 0
while (true) {
int in = sc.nextInt();
if (in==42) break;
list.add(i++,sc.nextInt())
}
for(int i=0;i<list.size();i++)
{
out.println(list.get(i));
}
}
}
answered Jun 24, 2018 at 16:40
1 Comment
Siddharth Gupta
I wanted to stop taking input when the one of the inputs become 42 thats why I used list.get(i) != 42. Can you help me with that?
Explore related questions
See similar questions with these tags.
list.get(i)!=42
to do when the list is empty?