Codes, Java

First Java Assignment [part I]

We have our first assignment on Java.


/**
 * Name : Duc Ho.
 * Class : MATH410.
 * Prof. : Lonnie Bowe.
 * Obj. : +Using Scanner to read a line
 *        +Count the number of Words
 *        +Count the number of Chars, excluding the character [space]
 * IDE : Eclipse
 * Compiler : Java SE 1.7.0.
 * Date : 02/05/2012.
 */

import java.util.*;
import java.io.*;

public class DucHoA1P1a {

 /**
 * Main Methods.
 * @param args - the string of arguments passed in to the program.
 */
 public static void main(String[]args){
 System.out.print("Input the line: ");

 Scanner sc = new Scanner(System.in);
 String line = "";

 int numberOfWords = 0; //count the words
 int numberOfChars = 0; //count the chars

 //get the line
 line = sc.nextLine();
 line += "\n";

 for (int i = 0; i < line.length(); ++i){

 if (((line.substring(i,i+1)).contentEquals(" "))
    || ((line.substring(i,i+1)).contentEquals("\n")))
    numberOfWords++;
 else numberOfChars++;
 }

 System.out.println("The number of words are : " + numberOfWords);
 System.out.println("The number of chars are :" + numberOfChars);

 }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s