java.lang.ArrayIndexOutOfBoundsException while finding prime Number and creating array with it -
target - find primenumbers , create array what done - created method primereturner - homecoming true if number prime -
private static boolean primereturner (int i){ (int j=2;j<i; j++){ if (i%j==0) homecoming false; } homecoming true; } created method creating numbers prime numbers
private static void simplearray() { int []a = new int [100]; a[0]=1; a[1]=2; (int i=2; i<a.length; i++){ if (primereturner(i)==true){ a[i]=i; i++; } } } problem - errors during creating array - of item array 0 , ok... , times homecoming errors...
questing - wrong method simplearray?
a little bit modify code - recognize prime numbers , create array it, after adding 100th item in array errors
code
private static void simplearray() { int []a = new int [100]; a[0]=1; a[1]=2; int count=2; while (count<100) (int i=3; ; ++i){ if (primereturner(i)==true){ a[count]=i; count++; } } (int j=0; j<a.length; j++){ system.out.print(" " + a[j]); } } private static boolean primereturner (int i){ (int j=2;j<i; j++){ if (i%j==0) homecoming false; } homecoming true; } and main function public class exercise_1 { private static int select;
public static void main (string[]args) throws ioexception{ system.out.println("menu:"); .... system.out.println("array simple numbers - come in 7"); select = getnumber (); switch (select){ ..... case 7:{ simplearray(); } } } as result array prime number succsesfull created during printing array java.lang.arrayindexoutofboundsexception errors...
how resolve error?
you i++ in if(primereturner(i)) == true) block. in add-on for loop i++. you'll arrayindexoutofboundsexception because i index reach value greater 100, array max size. remove i++ in if block.
java arrays exception loops indexoutofboundsexception
No comments:
Post a Comment