Reputation:
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?
Upvotes: 3
Views: 104
Reputation: 997
Currently , you are getting into an infinite loop as a gets set to the first number and then keeps looping, thus, keeps adding same number to the list. you need to add inside the while loop. int a = s.nextInt();
Upvotes: 0
Reputation: 1802
Your problem is the below code:
while(a > 0) {
myList.add(a);
if (a == 0){
break;
}
}
As you can see after reading the first user input and assigning it to a
, the the while loop is running infinitely. This happens because the condition argument which is the a
variable never changes.
So you have to insert the part of code that updates that variable inside the while loop. Below is a simple fix:
Scanner s = new Scanner(System.in);
int a = 1;
List<Integer> myList = new ArrayList<>();
while(a > 0) {
a = s.nextInt();
if (a == 0) {
break;
} else {
myList.add(a);
}
}
Upvotes: 0
Reputation: 448
Please correct your loop
List<Integer> myList = new ArrayList<>();
while(true) {
int a = s.nextInt();
if (a == 0){
break;
} else
myList.add(a);
}
Upvotes: 0
Reputation: 4549
at least one a >= 0 needed for break to execute:
while(a >= 0) {
myList.add(a);
if (a == 0){
break;
}
}
Upvotes: 1