i'm having a hard time creating a program that will display the initials of a string provided by the user. The program should also display the number of words of a given string. i've tried this code, but the problem is, the program would only display the first initial and would only count one word.

this is the code:

import java.util.Scanner;

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

        String statement = " ";
        int counter = 0;

        System.out.print ("Enter a String: ");
        statement = in.nextLine ();
        statement.length();

        System.out.println ("Initial of the String: ");
        for (int i = 0; i < statement.length(); i++){
            if ((statement.charAt (i) != ' ') && (i == 0)) {
                System.out.println (statement.charAt (i) + " ");
                counter ++;
            }
        }

        System.out.print ("Word Count: " + counter);

    }
}

You have a choice of strategies, including:

Old-fashioned programming: In your loop look at two chars (eg charAt(i) and charAt(i-1)) so you can detect all cases where a blank is followed by a non-blank (ie the start of a word). You'll have the special-case the very first char in the String, but you already have code to do that kind of thing.

Smart use of the Java API: use the split method in the String class to split your text up into words with one simple call. YOu will find the full dexcription of that method in the Java API doc under the String class.

Propbably this what you needed.

public static void main(String args[]) {
        String str = "King Narega";//assuming  this is the input string from system.in
        String[] strParts=str.split(" ");
        for (String part:strParts){
            System.out.println("------->"+part);
        }
        System.out.println("Initials-->"+strParts[0]);
        System.out.println("Counter--->"+strParts.length);     
}

The sample output is given here
------->King
------->Narega
Initials-->King
Counter--->2

@subramanya.vl

Here at DaniWeb we try to help people learn Java and develop their Java skills. We do NOT do people's homework for them. Your post explains and teaches nothing, it just gives the OP a chance to cheat. In future please help by pointing people in the right direction - eg tell them which classes and methods they should read about. If you need to explain with actual code then explain why you coded it the way you did. Don't just spoon-feed them a solution to copy and paste.

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.