I'm trying to add user's input into list and then show it in reverse order. The elements are added until the user enters 0. Here's my code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class InputInArrrayList{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
List<Integer> myList = new ArrayList<>();
while(a > 0) {
myList.add(a);
if (a == 0){
break;
}
}
Collections.reverse(myList);
System.out.println(myList);
}
}
But the loop doesn't break when it's 0. Instead, it throws OutOfMemoryError: Java Heap space. What am I doing wrong?
at least one a >= 0 needed for break to execute:
while(a >= 0) {
myList.add(a);
if (a == 0){
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With