exception - Java Arraylist got java.lang.IndexOutOfBoundsException? -
i'm general 3d artist, switched career , started learn programming. i've got problem c106a handout #5.
the code works, i've still got error log here.
exception in thread "main" java.lang.indexoutofboundsexception: index: 4, size: 4 @ java.util.arraylist.rangecheck(arraylist.java:547) @ java.util.arraylist.get(arraylist.java:322) @ uniquenames.showunique(uniquenames.java:23) @ uniquenames.main(uniquenames.java:39)
why arraylist
, can stretch capacity on own, still outofboundsexception
?
here's full code:
import acm.io.*; import acm.program.consoleprogram; import acm.util.*; import java.io.*; import java.util.arraylist; import java.lang.*; public class uniquenames extends consoleprogram{ static arraylist<string> mestring = new arraylist<string>(); static string input ; public static void storeunique(string input){ if (!mestring.contains(input)) { mestring.add(input); } } public static void showunique(arraylist<string> mestring){ system.out.println("unique name list contains:"); for(int i=0 ;i<= mestring.size() ;i++){ system.out.println(mestring.get(i)); } } public static void main(string[] args){ try{ inputstreamreader stream = new inputstreamreader(system.in); bufferedreader br = new bufferedreader(stream); while (true){ system.out.println("enter name:"); string input = br.readline(); if (input.equals("")) break; storeunique(input); } {showunique(mestring);} } catch(ioexception e){ } } }
the following lines:
for (int = 0; <= mestring.size(); i++) { system.out.println(mestring.get(i)); }
should be:
for (int = 0; < mestring.size(); i++) { system.out.println(mestring.get(i)); }
this because index of list starts zero.
index: 4, size: 4
explains little more. when call get(4)
, exception occurs because list has size of 4. get(4)
attempt access 5th element in list.
valid elements can access get(0)
, get(1)
, get(2)
, get(3)
.
Comments
Post a Comment