find the no of characters,blank spaces and words

the only thing i get right is the no of characters

Page 1 of 1

2 Replies - 2013 Views - Last Post: 01 May 2009 - 12:09 PM Rate Topic: -----

#1 aneesha  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 23-April 09

find the no of characters,blank spaces and words

Post icon  Posted 01 May 2009 - 03:32 AM

import java.io.*;
import java.util.*;
class Word
{
public static void main(String args[])
{
String str=new String("i am a programmer");
int count1=0,count2=0,count3=0,count4=0;
int i;
boolean flag=false;
char ch[]=new char[str.length()];
for(i=0;i<str.length();i++)
{
count3++;
if(ch[i]==' ')
{
count1++;
count2++;
}
else if(ch[i]==' '&& ch[i+1]==' ')
count4++;


}
System.out.println("number of words="+((count2)+1));
System.out.println("number of blank spaces="+count1);
System.out.println("number of characters="+count3);
}
}

Is This A Good Question/Topic? 0
  • +

Replies To: find the no of characters,blank spaces and words

#2 ayman_mastermind  Icon User is offline

  • human.setType("geek");
  • member icon

Reputation: 126
  • View blog
  • Posts: 1,860
  • Joined: 12-December 08

Re: find the no of characters,blank spaces and words

Posted 01 May 2009 - 04:30 AM

Please add your question within the post and not in your title description, in addition please be a little more descriptive about your problem and paste your code within code tags :code: Thank you for helping us help you :)
Was This Post Helpful? 0
  • +
  • -

#3 Mikeyp926  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 29
  • View blog
  • Posts: 205
  • Joined: 20-March 09

Re: find the no of characters,blank spaces and words

Posted 01 May 2009 - 12:09 PM

Some suggestions.

Rename your count variables with more meaningful names. What are they counting?
count1 could be something like blankSpaces
count2 could be something like words
count3 could be something like chars

and what are you doing with count4?

Also, there are much easier ways to do this without storing the array of chars. To get the number of characters just use str.length(). And to get the number of spaces and words you could just use a string tokenizer with a space as the token.

Did you have any specific problems or questions about your code that you posted?

This post has been edited by Mikeyp926: 01 May 2009 - 12:09 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1