I am just starting out at JAVA and trying to write a program that counts all characters in a string, counts all characters minus trailing and leading blanks and also counts all non-blank characters. Here is what I have so far. I am stuck on the non-blank character counts. Can anyone provide some help on this? The countChar always returns 0...

import java.util.Scanner;

public class Count {

	public static void main(String[] args) {
		
		for (int count = 1; count <= 5; count ++) {
		
		System.out.println("Please enter some text: ");
		Scanner keyboard = new Scanner(System.in);
		String text = keyboard.nextLine();
		
		int HowLong = text.length();
		String MinusTrailing = text.trim();
		int CMinusTrailing = MinusTrailing.length();

		String NB = MinusTrailing;
	    int countChar = 0;
	    int limit = NB.length();
	
	    for(int i = 0; i < limit; ++i)
	    {		  
	      if(Character.isWhitespace(NB.charAt(i)))
	        {		  
		      ++count;
	      }
	        }	 		
				
		System.out.println(HowLong);
		System.out.println(CMinusTrailing);
		System.out.println(countChar );
	
	
		}
		
	}

}

Thanks!

I think you want to increment "countChar "instead of "count" in this statement

if(Character.isWhitespace(NB.charAt(i)))
 {
   ++count;
 }

:)

I think you want to increment "countChar "instead of "count" in this statement

Got it!! Thank you so much!!!

int countChar = string.replaceAll("\\s*", "").length();

Just to be an @ss! ;-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.