Search code examples
javanew-operator

(Java)Using while function with condition


I am making program that add all the number from user input until 0 comes. when 0 comes as input, I want to show all the numbers that are saved. When I run the program I got the "java.lang.OutOfMemoryError: Java heap space" this error and I want to know what part is wrong.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    ArrayList<Integer> myList = new ArrayList<Integer>();
    int a = scanner.nextInt();
    
    while(a!=0) {
        myList.add(a);
    }
    for(int i=0;i<myList.size();i++) {
        System.out.println(myList.get(i));
    }

Solution

  • IMHO a for loop is more appropriate:

    for (int a = scanner.nextInt(); a != 0; a = scanner.nextInt()) {
        myList.add(a);
    }
    

    This has the desirable effect of limiting the scope of a to the loop (one should always limit the scope of everything as much as possible).