1

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
3
  • Use debugger and it will obvious. Commented Jun 24, 2018 at 16:25
  • What are you expecting list.get(i)!=42 to do when the list is empty? Commented Jun 24, 2018 at 16:25
  • your list is empty, also you must use try-catch while iterating such lists and list starts from 1 not 0. Commented Jun 24, 2018 at 16:27

1 Answer 1

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

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?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.