The Way to Programming
The Way to Programming
I tried to run program, after first correct output (number 32) , I get this:
Exception in thread "main" 32 java.lang.IndexOutOfBoundsException: Index: 6, Size: 6 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at Rad.out(Rad.java:44) at Rad.main(Rad.java:25)
I think that I attempting to access an index that doesn’t currently exist in the ArrayList.
How to fix this problem in code?
import java.util.*; public class Rad { public static ArrayListheap = new ArrayList (); public static Scanner cin = new Scanner(System.in); public static void main(String[] args) { heap.add(0); int n,x; n = cin.nextInt(); for (int i = 0;i < n;i++) { x = cin.nextInt(); ubaci(x); } int m,y; m = cin.nextInt(); for (int i = 0;i < m;i++) { y = cin.nextInt(); if (y == 0) { if (heap.size() > 1) { System.out.println(heap.get(1)); izvadi(); } else System.out.println("Nema!");} else ubaci(y); } System.exit(0);} public static void ubaci(int x) { heap.add(x); int t = heap.size()-1; while (((t/2)!=0) && heap.get(t)>heap.get(t/2)){ int temp = heap.get(t/2); heap.set(t/2, heap.get(t)); heap.set(t, temp); t/=2; } } public static void izvadi() { heap.set(1, heap.get(heap.size())); heap.remove(heap.size()); int t = 1, r; while(true) { if (t*2+1 < heap.size()) { if(heap.get(t*2) > heap.get(t*2+1)) r = t*2; else r = t*2+1; } else if(t*2 < heap.size()) r=t*2; else break; if(heap.get(r) > heap.get(t)) { int temp = heap.get(t); heap.set(t, heap.get(r)); heap.set(r, temp); t = r; } else break; } }}
Input: 5 15 32 4 18 29 12 0 0 50 0 24 97 0 0 0 0 0 0 Print: 32 29 50 97 24 18 15 4 No
When input is 0, output is largest number in heap.If input is some other number,then it is stored in heap.
Accessing the # element that doesn’t exist because of the size() method. Size() method brings the actual size of the heap.
EX: You add 3(a,b,c) items their positions are the following 0 = a, 1 = b, 2 = C. When you heap.get(heap.size()) you are accessing the element in position 3 which doesn’t exist. You must call
heap.set(1, heap.get(heap.size() - 1));
Sign in to your account