+ 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"
10 Answers
+ 2
your mistake may be the semicolon which you have inserted after the for loop .
+ 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.
+ 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.
0
I am not sure, but I think it should be l=s.length; , not l=s.length();
0
.length() is a method so it MUST have these brackets even if there are no parameters, thanks for trying
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);
0
Can anybody tell me how the coding done for printing the number of words in the sentence?
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.
0
Ah thats what I thought you wanted, i misunderstod you sry
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