So I’m trying to make a program that sorts 10 numbers, and I wanted to used an ArrayList. However, whenever I run my program it gives me the error: java.lang.OutOfMemoryError: Java heap space
, and I can’t figure out why. I’ve tried looking up causes, but none seemed to work. I’d like to understand why this error is happening so it doesn’t happen in the future when programming the robot.
Here is the code, thank you in advance for any help
import java.util.*;
public class SortNumbers
{
public static void main(String args[]){
//Creating the neccassary Objects
Scanner scan = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
int input;
//Ask the user to input 10 numbers
System.out.println("Please enter 10 integers");
//Enter the numbers and sort them into the array
input = scan.nextInt();
numbers.add((Integer) input);
for(int i = 0; i < 10; i++){
input = scan.nextInt();
//Sort the numbers immediatly into the ArrayList
for(int j = 0; j < numbers.size(); j++){
//If the number is lest the current index, inset the number at that index
if(input < numbers.get(j).intValue()) numbers.add(j, (Integer) input);
}
//If the number is greater than the last element, add it to the end of the list
if(input > numbers.get(numbers.size()-1).intValue()) numbers.add((Integer) input);
}
//Print out the sorted array
System.out.println("The numbers in sorted order: ");
for(Integer num : numbers) System.out.println(num);
}
}