1.11M Members

Count characters in a code

 
0
 

I am trying to get this program to count the number of characters in a string. By number of characters l mean not punctuation or a space.What is wrong with my code because l don't understand why the program won't work?

import javax.swing.*;

publiemc class ExamPractise
{
	public static void main (String [] geek)

	{
		String sentence = JOptionPane.showInputDialog("Enter a any sentence");

		
		int countCharacters=0;



       for (int i = 0; i < sentence.length(); i++)
       {
		   char c = sentence.charAt(i);		  
			
			    
			    	if (c !=' '||c!='?'||c!='.'||c!=' ')
			    	{
						countCharacters++;
					}
	   }


		  System.out.println("There are" + " " + countCharacters + " " + "word");


	}
}
 
0
 
[B]publiemc [/B]class ExamPractise

Make it public

And:

if (c !=' '||c!='?'||c!='.'||[B]c!=')[/B]
{
       countCharacters++;
}

^What do you wanna c not to be there?


Should be find after that.
-----

And I checked out the program, it still counts for spaces and punctuation.

EDIT AGAIN

Since your counting the characters you should make you if statement to check the ASCII value for an example:

if ((c >= 65 && c > 91))
{
	countCharacters++;
}

That will check for uppercase letters only. Heres an ascii table.
http://web.cs.mun.ca/~michael/c/ascii-table.html

Just OR it with the other conditionals you make i.e.

if ((c >= 65 && c > 91) || (lower case condition) || (numbers condition))
{
	countCharacters++;
}
 
0
 
[B]publiemc [/B]class ExamPractise

Make it public

And:

if (c !=' '||c!='?'||c!='.'||[B]c!=')[/B]
{
       countCharacters++;
}

^What do you wanna c not to be there?


Should be find after that.
-----

And I checked out the program, it still counts for spaces and punctuation.

Right now if l enter the word Obama Obama ? it counts the question mark and space between the two words as a character and l don't want it to do that.I don't know how do l get around that ?

 
0
 

Right now if l enter the word Obama Obama ? it counts the question mark and space between the two words as a character and l don't want it to do that.I don't know how do l get around that ?

Check out the ASCII table above I edit my post, the upper case condition is checked for, just check for the other two. And it will eliminate the characters that aren't a letter and number.

 
0
 

try using this method to check each character:

if (Character.isLetter(c)) {
countCharacters++;
}


don't forget, you'll need to import java.lang.Character;

 
0
 

> By number of characters l mean not punctuation or a space

Look into the isLetter method of the Character class; modify your logic to increment the count only if the above method returns true .

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article