Array index out of bound exception for palindrome java program -



Array index out of bound exception for palindrome java program -

why getting array bound of exception? im beginner in programming. please help me understand. have tried convert string char array , reverse characters , convert end result string , compare original string

/* check if entered string palinrome or not*/ class palin { public static void main(string[] args) { string name="anna"; int l=name.length(); int d=l/2; char tmp; char tmp1; char[] arr = name.tochararray(); for(int j=0;j<d;j++) /*to swap characters*/ { tmp=arr[j]; tmp1=arr[l]; arr[j]=tmp1; arr[l]=tmp; l=l-1; } string str=string.valueof(arr); /* convert swapped char array string*/ if (str==name) system.out.println("true"); else system.out.println("false"); } }

an array of n entries can accessed index between 0 , n-1.

change this:

tmp1 = arr[l];

to this:

tmp1 = arr[l-j-1];

and rid of this:

l = l-1;

by way, swapping can done in 3 assignment operations instead of 4.

so might alter this:

tmp = arr[j]; tmp1 = arr[l]; arr[j] = tmp1; arr[l] = tmp; l = l-1;

to this:

tmp = arr[j]; arr[j] = arr[l-j-1]; arr[l-j-1] = tmp;

java arrays indexoutofboundsexception palindrome

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -