Homework #5
MENU
Main Page

CIS 602

Homework #1
Homework #2
Homework #3
Homework #4

Homework #5

Homework #6
Homework #7
Homework #8
Homework #9
Homework #10
Homework #11

Time sheet
Alex RudniyTime Sheet 
DateTimeTaskTime spent (hrs)
13-Feb-0601-30 PMRead textbook2
14-Feb-0611-00 AMRead Lecture1
14-Feb-0612-00 PMPlanning1
15-Feb-0602-30 PMWrite applications4
8


4.1 FACTORIAL
Planning document

USE CASE: FACTORIAL

Scope: Factorial calculating application

Primary actor: person who calculates a factorial

Stakeholders and interests:

-          Person who calculates a factorial: Desires accurate and fast calculation.

Preconditions:

Integer values between 0 and 31 are accepted on input;

One command line parameter is expected;

The user should be able start an application from console;

J2SE installed on user’s PC.

Main scenario

Input Events from User

System Events and Responses

Start application with accepted parameter

Calculate a factorial

 

Display a result

 

Extensions

A.    User runs an application without parameter.

Generate message how to use application. Quit application.

B.     User inputs a parameter less than 0.

Generate error message. Quit application.

C.     User inputs a parameter greater than 31.

Generate error message. Quit application.

D.    Any other error.

Generate error message. Quit application.


Inspection document

1. Bad format
2. Some comments should be there to make the code more understandable for an inspector


Code

/**
*  This program calculates the factorial of n integer values.
*/

public class Factorial{
   public static void main(String[] args){
     if (args.length < 1 ) {		//if no parameters, we tell how to use it
       System.out.println("Usage: java Factorial integer");
     }
     else {
       try {
       
         int n = Integer.parseInt(args[0]);
         int fct = 1;
       
         // try to handle different values of n 
         if ((n >= 0) && (n < 32)) {
		   
		   if (n > 0) {
		     for (int i = 1; i <= n; i++){
               fct *= i;
             }
		   }

		   System.out.println(n + "! = " + fct);
	     }
         if (n >= 32){
           System.out.println("This number is too big so integer type can't handle it.");
         }
		 if (n < 0){
		   System.out.println("This number should be greater or equal to 0.");
		 }
	   } catch (Exception e) {
		 System.out.println("I'm sorry! An error occurs");
		 System.out.println("Usage: java Factorial integer");
       }
     }
   }
}

4.2 AVERAGE
Planning document

USE CASE: AVERAGE

Scope: Calculation of average of list of integers application

Primary actor: person who calculates an average

Stakeholders and interests:

-          Person who calculates an average: Desires accurate and fast calculation.

Preconditions:

A text file containing integer values;

One command line parameter is expected;

The user should be able start an application from console;

J2SE installed on user’s PC.

Main scenario

Input Events from User

System Events and Responses

Start application with file name as a parameter

Read values from a file

 

Calculate sum of values

 

Calculate the quantity of values

 

Calculate an average value

 

Display a result

 

Extensions

A.    User runs an application without parameter.

Generate message how to use application. Quit application.


Code
/**
* This program calculates the average of a list of integers.
*/

import java.io.*;

public class Average {

  public static void main (String[] args){
    if (args.length >= 1) {
        try{
	      BufferedReader in = new BufferedReader(
		                      new FileReader(args[0])); 
		  String  line;
		  int counter = 0;
		  int sum = 0;

	      while ((line = in.readLine()) != null) {

            sum += Integer.parseInt(line);    //calculate sum
            counter++;						  //increase counter
          }
          sum /= counter;                     //finally calculate average
          System.out.println("Average of " + counter + " integers is " + sum);

        } catch (IOException e) {
		  System.out.println("Usage: java Average file_name");
		}
    }
	else {
	  System.out.println("Usage: java Average file_name");
	}
	
  }
}


4.3
Planning document

USE CASE: E-MAIL IDs

Scope: E-mail ID generating application

Primary actor: person who generates e-mail IDs

Stakeholders and interests:

-          Person who generates e-mail IDs: Desires accurate and fast result.

Preconditions:

Text file containing formatted strings with last name, first name, SSN;

Text file to store results;

The user should be able start an application from console;

J2SE installed on user’s PC.

Main scenario

Input Events from User

System Events and Responses

Start application

Open input file for reading

 

Open output file for writing

 

Read lines

 

Generate e-mail IDs

 

Save output file

 

Extensions

A.    Wrong information in input file or any other error occurs.

Generate message how to use application. Quit application.


Code
import  java.io.*;

/**
* This program generates student e-mail IDs.
* input file is students.txt, output file is studentemail.txt
*/
public class Email {

  public static void main(String[] args) {
    try {
	  BufferedReader in = new BufferedReader(
						  new FileReader("students.txt"));
      PrintWriter out = new PrintWriter(
	  		            new BufferedWriter(
				        new FileWriter("studentemail.txt")));
	  
	  String  line, eml="";
	  int begin = 0, end;
	  char delim = ':';
	  
	  while ((line = in.readLine()) != null) {
	    end = line.indexOf(delim, begin);
		eml = line.substring (end+1, end+2) + line.substring (0,1) + 
			  line.substring (line.length() - 4, line.length()); //generate e-mail ID
		eml += "@njit.edu";			    // add domain to ID
		out.println(eml.toLowerCase()); // write ID to output file
	  }

	  out.flush();
	  out.close();

      } catch (IOException e) {
	    System.out.println("Usage: java Email");
	  }
    
  }

}



4.7 CREATE PACKAGE
Planning document

PACKAGE
Scope: Create package from existing classes

1. Create directories for package
2. Copy classes to package directory
3. Add “package line” to classes source
4. Recompile applications
5. Run each application

Code
I put programs to a such directory \myprog\single\
I have only added one line at the beginning of every code:
package myprog.single;
Than I recompiled programs and started them.

4.8 IMPROVED AVERAGE
Planning document

USE CASE: IMPROVED AVERAGE

Scope: Calculation of average of list of integers

Primary actor: person who calculates an average

Stakeholders and interests:

-          Person who calculates an average:

1.      Accurate and fast calculation

2.      Exception handling with a meaningful message

3.      Application should ignore any lines in the input file that are other than a single integer

 

Preconditions:

A text file containing integer values;

One command line parameter is expected;

The user should be able start an application from console;

J2SE installed on user’s PC.

Main scenario

Input Events from User

System Events and Responses

Start application with file name as a parameter

Read values from a file

 

Check string value

 

Calculate sum of values

 

Calculate the quantity of values

 

Calculate an average value

 

Display a result

 

Extensions

A.    User runs an application without parameter.

Generate message how to use application. Quit application.

            B. Input file contains more than one integer or garbage in a line

                  Skip the line without a message and continue calculation

            C. Any other error.

                 Submit meaningful message matching a kind of error


Code
/*
*   This pogram prints out the average of the integers supplied in the variables.txt file
*   
*/
import java.io.*;

public class Average {

  public static void main (String[] args){
    if (args.length >= 1) {
      try{
	    BufferedReader in = new BufferedReader(
	  	   				    new FileReader(args[0]));

	    String  line;
	    int counter = 0;
        int sum = 0;
		boolean notInteger = false;
		
	    while ((line = in.readLine()) != null) {
		
		  for (int i=0; (i < line.length()); i++) {
		   		  
			notInteger = false;
			// if line contains not an integer we skip this line without any message
			if ((!line.substring(i,i+1).equals("0")) && (!line.substring(i,i+1).equals("1")) && 
				(!line.substring(i,i+1).equals("2")) && (!line.substring(i,i+1).equals("3")) && 
				(!line.substring(i,i+1).equals("4")) && (!line.substring(i,i+1).equals("5")) && 
				(!line.substring(i,i+1).equals("6")) && (!line.substring(i,i+1).equals("7")) && 
				(!line.substring(i,i+1).equals("8")) && (!line.substring(i,i+1).equals("9"))) {
			  notInteger = true;
			  
    	    }
			
		  }
		  
		  // calculate the sum, increase counter
		  if (notInteger == false) {
		    sum += Integer.parseInt(line);
		    counter++;
          }
		    
        }
		
		//calculate average, print out the result
        sum /= counter;
		System.out.println();
        System.out.println("Average of " + counter + " integers is " + sum);

      }  catch (IOException e) {
		 System.out.println();
	     System.out.println("The file doesn't exist. Please, specify another one!");

      }  catch (NumberFormatException e) {
		 System.out.println();
	     System.out.println("Incorrect value in the input file. Please, specify another one!");
	  
	  }	 catch (ArithmeticException e) {
		 System.out.println("Sorry. Some kind of arithmetic error!");	

	  }
    }
	else {
      System.out.println();
	  System.out.println("Usage: java Average a_file_name");  // if incorrect file name
	}
  }
}