user5974397
user5974397

Reputation:

Counting white-spaces in a String in java

I have written a program which takes a String as user input and displays the count of letters, digits and white-spaces. I wrote the code using the Tokenizer-class, and it counts the letters and digits, but it leaves out the white-spaces. Any ideas?

import java.util.Scanner;

public class line {

  public static void main(String[] args) {

    System.out.println("Enter anything you want.");
    String text;
    int let = 0;
    int dig = 0;
    int space= 0;

    Scanner sc = new Scanner(System.in);
    text = sc.next();
    char[]arr=text.toCharArray();

    for(int i=0;i<text.length();i++) {
        if (Character.isDigit(arr[i])) {
            dig++;
        } else if (Character.isLetter(arr[i])) { 
            let++;
        } else if (Character.isWhitespace(arr[i])) {
            space++;
        }
    }
    System.out.println("Number of Letters : "+let);
    System.out.println("Number of Digits : "+dig);
    System.out.println("Number of Whitespaces : "+space);
  }          
}

Upvotes: 4

Views: 3266

Answers (4)

dhruv jadia
dhruv jadia

Reputation: 1680

Try using

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Line {
 public static void main(String[] args) throws Exception {
  String s;
  System.out.println("Enter anything you want.");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  s = br.readLine();
  int length = s.length();
  int letters = 0;
  int numbers = 0;
  int spaces = 0;
  for (int i = 0; i < length; i++) {
   char ch;
   ch = s.charAt(i);
   if (Character.isLetter(ch)) {
    letters++;
   } else {
    if (Character.isDigit(ch)) {
     numbers++;
    } else {
     if (Character.isWhitespace(ch)) {
      spaces++;
     } else
      continue;
    }
   }
  }
  System.out.println("Number of letters::" + letters);
  System.out.println("Number of digits::" + numbers);
  System.out.println("Number of white spaces:::" + spaces);
 }
}

Upvotes: 0

Pallav Jha
Pallav Jha

Reputation: 3629

Instead of text = sc.next(); use text = sc.nextLine();

Upvotes: 0

Thodgnir
Thodgnir

Reputation: 148

You have got problem in

sc.next();

except it, use

sc.nextLine();

it should work.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234885

Scanner by default breaks the input into tokens, using whitespace as the delimiter!

Simply put, it gobbles up all the whitespace!

You can change the delimiter to something else using sc.useDelimiter(/*ToDo - suitable character here - a semicolon perhaps*/).

Upvotes: 2

Related Questions