+ 1

Please help me my code doesn't work 😭 😭 java course : Word counting and Character counting 🥺

The output shows Exception in thread "Main" java.stringIndexOutOfBoundException I don't get it what it says import java.util.Scanner; public class Program { public static void main(String[] args) { String str; int size; int charCount=0,wordCount=1; Scanner sc= new Scanner(System.in); System.out.println ("Enter String"); str=sc.nextLine(); System.out.println("String Name \t\t:"+str); size=str.length(); System.out.println("String Length\t:"+size); for(int index=0;index<=size;index++){ if(str.charAt(index)!=' ') { charCount++; } if(str.charAt (index)==' ') { wordCount++; } }//end of for loop System.out.println("Character Count"+charCount); System.out.println("Word Count"+wordCount); } }

9th Jul 2023, 11:56 PM
Kaung Myo Htet
Kaung Myo Htet - avatar
3 Réponses
+ 5
Hey there! Change the line "index <= size" in the code, to "index<size", then it'll work perfectly. Always remember that indexing always start at 0! So, Indexing must be LOWER THAN the length of the given string. (Explanation: It raises stringIndexOutOfBoundException, because in your code, indexing starts at 0, and ends with the length of the given string. So, you are trying to get the element of an index that doesn't exist.)
10th Jul 2023, 2:10 AM
Dragon RB
Dragon RB - avatar
+ 1
Tysm sir 😍😍
10th Jul 2023, 3:24 AM
Kaung Myo Htet
Kaung Myo Htet - avatar
0
How to make program
11th Jul 2023, 1:39 PM
Emon Roy
Emon Roy - avatar