I tried taking input in ArrayList but it shows out of memory

Viewed 40

I tried taking input in ArrayList but it shows out of memory. can anybody see whats wrong? first i created takeInput to receive input till last number entered is -1. After that i made print function to print the code

Code-

 import java.util.*;
public class ArrayListTakeInput {
    /**
     * @return
     */
    public static ArrayList<Integer> takeInput(){
        ArrayList<Integer> list = new ArrayList<Integer>();
        Scanner s=new Scanner(System.in);
        int i=s.nextInt();
        while(i!=-1){

            list.add(i);
        }
        return list;


    
}

public static void print(ArrayList<Integer> list2){
    for(int i=0; i<list2.size(); i++) {
        System.out.print(list2.get(i) + " ");
    }
}
public static void main(String[] args) {
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    list2=takeInput();
    print(list2);

    
}
}
1 Answers

The problem is your condition of your while loop in the method takeInput(). Your Variable 'i' is not updated inside the loop. Currently you set i once and the while loop condition never become false. That is the reason why it shows out of memory. To avoid this mistake updat 'i' inside the loop. I guess you won't add the end operation of your methode (-1) so this could be a solution:

import java.util.*;

public class ListTakeInput {
    /**
     * @return
     */
    public static List<Integer> takeInput() {
        List<Integer> list = new ArrayList<>();
        Scanner s = new Scanner(System.in);
        int i = s.nextInt();

        while (i != -1) {
            list.add(i);
            i = s.nextInt();
        }

        return list;

    }

    public static void print(List<Integer> list2) {
        for (Integer integer : list2) {
            System.out.print(integer + " ");
        }
    }

    public static void main(String[] args) {
        List<Integer> list2 = takeInput();
        print(list2);
    }
} 
  
Related