By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Count Specified Word - Java Task

+7 votes

Write a program to find how many times a word appears in given text. The text is given at the first input line. The target word is given at the second input line. The output is an integer number. Please ignore the character casing. Consider that any non-letter character is a word separator.


count words in java

asked in Java category by user eiorgert
edited by user golearnweb

1 Answer

+1 vote
Best answer

Here'e my solution mate:

import java.util.ArrayList;
import java.util.Scanner;

public class Pr_06_CountSpecifiedWord {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(;
        String[] firstIn = scanner.nextLine().toLowerCase().split("((\\s+)|('))");//EMPTY SPACES + APOSTROPHE
        String secondIn = scanner.nextLine().toLowerCase();//THE SECOND INPUT IS LOWER CASE AS WELL - SO BOTH CAN MATCH

        int counter = 0;
        for (int i = 0; i < firstIn.length; i++) {
            if (firstIn[i].equals(secondIn)) {//IT IS BETTER TO USE .equals then == !!! WHEN COMPARING STRINGS

Here's how you should compare strings in Java:

answered by user hues
edited by user golearnweb