Friday, December 23, 2011

Tutorial: Word Counts Program using Java

by eturo


I still remember when my teacher in Java programming (Basic Programming) gave us a hands-on lab activity that goes this way:

Problem:

Create a Java program that will allow the user to enter or type any string (phrase/paragraph in any length), then the program has the ability to count the number of words within that phrase or paragraphs.

Solution:

import java.util.Scanner;

public class countWords {
 public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  String s;
  int counter = 0;
  boolean startOfWord = false;

  System.out.print("Enter a string: ");
  s = in.nextLine();

  for(int i = 0; i < s.length(); i++) {
   if(s.charAt(i) != ' ') {
    if(!startOfWord) {
     startOfWord = true; //change this into true, 
      coz the first character of a word is found
     counter++; //a word is found, so increment counter
    }
   }
   else {
    startOfWord = false;
   }
  }

  System.out.print("Number of words: " + counter);

 }

}


I used BlueJ text editor when I'm creating, compiling, running and debugging Java programs (like the image below). This text editor is very cool and nice to used. To download this, click this link. Browse down the page and got to Software category under Programming.




I got the answer in 2 hours for that very short code. (yipih!) Try it now and Happy coding!

Like Us on Facebook

Related Posts Plugin for WordPress, Blogger...