\\java.lang.ArrayIndexOutOfBoundsException | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

\\java.lang.ArrayIndexOutOfBoundsException

import java.util.Scanner; public class pigLatin { public static void main(String[ ] args){ Scanner input = new Scanner(System.in); String text = input.nextLine(); StringBuilder s1 = new StringBuilder (text); char[ ] c = new char[s1.length()]; s1.append(' '); c[0]= s1.charAt(0); s1.deleteCharAt(0); for( int i = 0; i<s1.length(); i++ ) { if( s1.charAt(i) == ' ') { for(int j = 1; j<s1.length(); j++) { c[j] = s1.charAt(i+1); s1.deleteCharAt(i+1); s1.insert(i, c[i-1]); s1.insert(i, "ay"); } } } System.out.println(s1); } } The above code can run and get user input but it can't print output as expect because of the exception. I think it probably due to output's capacity is greater than the input 's length... I've scratch my mind for an hour then I still have no idea. Could someone help me out, please!!? @@

8th Apr 2020, 9:38 AM
Le Hoang Tuan
Le Hoang Tuan - avatar
5 Answers
0
RnT.Lee By your approach, Ex if input is abcd efgh ijk You are starting copying when if(s1.charAt(i)==' ') by this starts at 'efgh' so you are missing 'abcd'. And doing it until s.length() so upto end not next space.. So should be j<i. And s1.charAt(i+1) when reaches end raises index out of exception. So make sure i+1 must less than s1.length. Next statement also...
8th Apr 2020, 10:45 AM
Jayakrishna 🇮🇳
0
you have two typos, first loop you used comma instead of semicolon for(int i =0, ) should be for(int i =0;) then you use C[j] while the original is not capital c. happens because of autocorrect I guess.
8th Apr 2020, 9:52 AM
Bahhaⵣ
Bahhaⵣ - avatar
0
Bahha🐧 I scanned this code from my laptop through an app on smartphone. :v It often occur typos as you see. But i tried the original code a lot of time, it still not work... :(((((
8th Apr 2020, 10:06 AM
Le Hoang Tuan
Le Hoang Tuan - avatar
0
Jayakrishna🇮🇳 I'm done! Thanks for your recommendation. 😅 Is the following code okay!? import java.util.Scanner; import java.util.StringTokenizer; public class Program { public static void main(String[] args) { Scanner input = new Scanner(System.in); String text = input.nextLine(); StringTokenizer s1 = new StringTokenizer(text); StringTokenizer s2 = new StringTokenizer(text); char [] c = new char[s2.countTokens()]; String [] S= new String[s2.countTokens()]; String [] S2= new String[s2.countTokens()]; int i = 0; while(s1.hasMoreTokens()){ c[i]=s1.nextToken().charAt(0); i++;} int p = 0; while(s2.hasMoreTokens()){ S[p]=s2.nextToken(); p++;} String val1= " "; String val2= " "; for(int j=0; j<S.length;j++){ val1 = S[j].substring(1); val2 = val1.concat(Character.toString(c[j])); S2[j]= val2.concat("ay");} for(String t:S2){ System.out.print(t+" ");} } }
9th Apr 2020, 2:53 PM
Le Hoang Tuan
Le Hoang Tuan - avatar
0
Working fine...
9th Apr 2020, 7:11 PM
Jayakrishna 🇮🇳