+ 6

Why does it say string out of bound?

The program must count the number of words here is my code : System.out.print("Enter a string: "); String s; s=input.nextLine(); int i,c=1,l=s.length(); for(i=0;i<l;i++); { if(s.charAt(i)==' ') c++; } System.out.println("Words ="+c); when I try to run it, it says "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4"

1st Oct 2018, 11:11 AM
Sara
Sara - avatar
10 Answers
+ 2
your mistake may be the semicolon which you have inserted after the for loop .
4th Oct 2018, 3:55 PM
Vivek Mishra
Vivek Mishra - avatar
+ 7
string indexing as array begins with 0 index. So if length = l you need use l-1 for your loop contidion. for( int i =0; i < l-1;i++) P.S Using l (lower L) as variable name is bad practice.
2nd Oct 2018, 2:48 PM
Sharofiddin
Sharofiddin - avatar
+ 2
I believe the mistake here is that you accidentally added a semi-colon after the closing parenthesis of your for-loop which increments 'i' to s.length(). Since arrays are indexed from 0, the last character of your string is at charAt(s.length()-1) but your program is now trying to access it at charAt(s.length()) and you get an off-by-one error. Removing the semi-colon solves the issue.
1st Oct 2018, 7:04 PM
Cluck'n'Coder
Cluck'n'Coder - avatar
0
I am not sure, but I think it should be l=s.length; , not l=s.length();
1st Oct 2018, 11:37 AM
Jan Ơtěch
Jan Ơtěch - avatar
0
.length() is a method so it MUST have these brackets even if there are no parameters, thanks for trying
1st Oct 2018, 12:43 PM
Sara
Sara - avatar
0
A easier way: Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String s=input.nextLine(); if(s.length() > 0){ System.out.println("Words = "+s.length()); } else{ System.out.println("String is empty"); } If you wanna use the loop you can doit like this: Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String s=input.nextLine(); int l = s.length(); for(int i=0;i<l;i++) { if(s.charAt(i)== l) l++; } System.out.println("Words = "+l);
1st Oct 2018, 2:29 PM
JavaBobbo
JavaBobbo - avatar
0
Can anybody tell me how the coding done for printing the number of words in the sentence?
2nd Oct 2018, 9:56 AM
Rachana C
0
JavaBobbo your code will work if I want to count the number of characters, it won't work in my case, thanks for trying.
5th Oct 2018, 7:06 AM
Sara
Sara - avatar
0
Ah thats what I thought you wanted, i misunderstod you sry
5th Oct 2018, 7:26 AM
JavaBobbo
JavaBobbo - avatar
0
import java.util.*; import java.util.Scanner; public class m { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter a string: "); String s; s=input.nextLine(); int i,c=1,l=s.length(); for(i=0;i<l;i++) { if(s.charAt(i)==' ') c++; } System.out.println("Words ="+c); } } //try this it's working
5th Oct 2018, 5:59 PM
abhilash chevella
abhilash chevella - avatar