Life,Universe and Everything

Please tell me why this shows runtime error…

import java.util.ArrayList;
import java.util.Scanner;

class Life_Universe_And_Everything {
 
	ArrayList<Integer> list=new ArrayList<Integer>();
	Scanner sc=new Scanner(System.in);
	public  void input()
	{
		int val;
		while(true)
		{
			val=sc.nextInt();
			if(val==-1)
				break;
			if(val>=0 && val<=99)
				list.add(val);
		}
	}
	public void display()
	{
			for(Integer a:list)
			{
				if(a==42)
					break;
				System.out.println(a);
			}
	}
	public static void main(String[] args) {
		
		Life_Universe_And_Everything lue=new Life_Universe_And_Everything();
		lue.input();
		lue.display();
	}
}

The problem with your code is that you are storing all the values input to the code is getting saved in the ArrayList which has a size limitation. So when the maximum size which the ArrayList can store gets filled up it throws an exception and hence you will get a Runtime error. So print only values till you get a number 42 as input and then stop taking the input.

I don’t know why it might give a TLE, but you shouldn’t use Scanner, it’s very slow in taking input, so you’ll lose time and solutions with the exact same algo will run faster(using InputStreamReader).