Aramza Aramza - 1 month ago 12
Java Question

Java: Counting Whitespace and Tabs

I am having trouble figuring out exactly how to get Java to spit out the amount of white spaces and tabs that are in a user inputted string. I used isWhiteSpace and all it counts is the amount of characters in the string.

I'd appreciate any help,

Thank you.

My Code:

import java.util.Scanner;

public class CharsInLine
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);

int numberUpperCase = 0;
int numberLowerCase = 0;
int numberWhiteSpace = 0;

System.out.print("Enter a line of text : ");
String inLine = console.nextLine();
int i = 0;

while ( i < inLine.length() ) {

char currentCharacter = inLine.charAt(i);

if ( Character.isUpperCase(currentCharacter) ) {
numberUpperCase++; }
if ( Character.isLowerCase(currentCharacter) ) {
numberLowerCase++; }
if( Character.isWhitespace(currentCharacter) ); {
numberWhiteSpace++; }

i++;

}

System.out.println("There are " + numberUpperCase + " upper case characters, " + numberLowerCase + " lower case characters, and " + numberWhiteSpace + " white space characters.");

console.close(); }
}

Answer

Your problem is here:

 if( Character.isWhitespace(currentCharacter) ); 

That trailing ";" on that line ... kills your if!

In other words, your code actually does this:

 if( Character.isWhitespace(currentCharacter) ) {
   ; 
 }
 {
    ... counter increase
 }

Your counter gets increased with each loop iteration. Thus ending up with the exact number of characters in the input!