Here’s a simple Java program that counts the number of words and characters in a given text:
import java.util.Scanner; public class WordCharacterCounter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a text: "); String text = scanner.nextLine(); int wordCount = countWords(text); int charCount = countCharacters(text); System.out.println("Number of words: " + wordCount); System.out.println("Number of characters: " + charCount); } public static int countWords(String text) { String trimmedText = text.trim(); if (trimmedText.isEmpty()) { return 0; } return trimmedText.split("\\s+").length; } public static int countCharacters(String text) { return text.length(); } }
This program takes user input as a string, counts the number of words and characters in it, and outputs the results.
The countWords
method counts the number of words in the given text by trimming it, checking if it is empty, and splitting it into words using whitespace as a delimiter. The countCharacters
method simply returns the length of the text string.
Note that the split
method in the countWords
method uses a regular expression ("\\s+"
) to split the text into words. This regular expression matches one or more whitespace characters, including spaces, tabs, and line breaks.
You can compile and run this program in any Java IDE or by running javac WordCharacterCounter.java
and java WordCharacterCounter
in the command line.
Word Count Example with Pad and Text Color:
Here’s an example of a word count program in Java that includes padding and text color:
import java.util.Scanner; public class WordCountExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a text: "); String text = scanner.nextLine(); System.out.println(); int wordCount = countWords(text); // Print the word count with padding and text color System.out.printf("%-30s %s%d%s%n", "Number of words:", "\033[1;32m", wordCount, "\033[0m"); } public static int countWords(String text) { String trimmedText = text.trim(); if (trimmedText.isEmpty()) { return 0; } return trimmedText.split("\\s+").length; } }
This program takes user input as a string, counts the number of words in it, and outputs the result with padding and green text color.
The printf
method is used to format the output with padding and text color. The %n
format specifier is used to print a new line character after the output.
The text color is specified using ANSI escape codes. The \033[1;32m
sequence sets the color to bold green, and the \033[0m
sequence resets the color to the default.
You can compile and run this program in any Java IDE or by running javac WordCountExample.java
and java WordCountExample
in the command line.