I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn\'t work. No matter what I write, I on
This is how i have done it :
It works fine too
import java.util.Scanner;
public class countwords {
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("Enter your sentence:[Try to ignore space at end]");
String s=in.nextLine();
System.out.println("Size of the string is "+s.length());
int res=count(s);
System.out.println("No of words in the given String --->>"+" "+s+" "+"is"+" :"+res);
}
private static int count(String s) {
// TODO Auto-generated method stub
int count=0;
if(s.charAt(0)!=' '){
count++;
}
for(int i=0;i
OUTPUT: this is my world bonaza
Size of the string is 23
No of words in the given String --->> this is my world bonazais :5
There are some bugs try to correct them and repost
A more simple way that i found was :
Just use this :
// Read a string
String st=s.nextLine();
// Split string with space
String words[]=st.trim().split(" ");