Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add input into list

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?


1 Answers

at least one a >= 0 needed for break to execute:

   while(a >= 0) {
        myList.add(a);
        if (a == 0){
            break;
        }
    }
like image 74
Pramod S. Nikam Avatar answered Sep 14 '26 05:09

Pramod S. Nikam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!