Numerology with Methods

From CompSciWiki
Revision as of 21:27, 1 April 2011 by EsmondP (Talk | contribs)

Jump to: navigation, search

Back to the Case Studies homepage

Problem

Write a complete Java program, similar to the problem Numerology in Case Studies Level Two. If you have not completed the previous problem click here to view problem details. Your goal is to rewrite the solution to use methods.


In particular, you should at least have methods with the following headers:

1. Calculate String Method

public static int calculateString (String name) 

This method will accept the name as a String and return the int which directly (i.e., without further collapsing)
corresponds to the name. So if name = “Alan Turing”, the method should return 45.


2. Collapse Integer Method

public static int collapseInt (int currentValue)

This method totally collapses the integer parameter currentValue to a single-digit number. So if currentValue = 88,
then the method should return 7 (and not 16).


3. Print Message Method

public static void printMessage (String name, int magicNumber)

This method should print the final message of the program. The magicNumber is between 1 and 9.


Remember to follow COMP 1010 coding standards.

 

Numerology with Methods

Wiki start01.jpg

Solution

The original solution looks similar to this.

import javax.swing.*;

public class A2Q2
{
    //Declare constants
                     .
                     .
                     .

    // main method
    public static void main(String [] args)
    {
	// declare and initialize variables
	                 .
                         .
                         .

	// read in user's name as a string
	                 .
                         .
                         .

	// calculate sum from name
	for (int r = 0; r < strName.length(); r++)
	{
	                 .
                         .
                         .
	}


	// collapse sum into a destiny number
	while(intDestiny >= 10)
	{
	                 .
                         .
                         .
        }

	// display destiny message
	if(intDestiny == 1)
	    System.out.println(strName + DESTINY_ONE);
        else if(intDestiny == 2)
	    System.out.println(strName + DESTINY_TWO);
	                 .
                         .
                         .
	else
	    System.out.println(strName + DESTINY_ERROR);
	}
}


Organize the Code

Separate the Statements

Separate Statements into Code Blocks

Add Comments to Explain the Code

Optimize the Code by Removing Unnecessary Variables

Fix the Errors in the Code

The messy code contained a total of eight different coding errors. Each error presented in this section is ordered as it appears in the code from the case study.

Add Code to Output Progress Reports as the Program Executes

Code

Solution Code

Back to the Case Studies homepage