Numerology with Methods

From CompSciWiki
Jump to: navigation, search

Back to the Case Studies homepage

Problem

Write a complete Java program, similar to the Numerology problem in Case Studies Level Two. If you have not completed the previous problem, you will need to view theproblem details to successfully complete this case study. 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

Before you code, I suggest you plan and create an outline of your solution. An outline can benefit you in many ways. For example an outline can help you determine the logic of your solution, variables, and methods. Additionally, you can find possible problems in the logic before writing any code. If an error exists or the code does not execute as expected, locating the problem in a few hundred lines of code is not always easy. If you know exactly what you want to do in advance, writing the code will be easier. We will follow a step by step process to solve the problem. Keep in mind these steps are just suggestions. Other programmers have there own techniques. Also, there are other possible solutions to the problem.


Here are steps you can follow:

  • Understand the problem
  • Summarize the problem into sections
  • Determine the logic for the solution
  • Organize the code
  • Type the rest of the code


Step 1: Understand the Problem

This step is important. You definitely want to avoid a situation where you have been working on an assignment for 3 days and suddenly find out you misinterpreted the question.


What is the Problem?

In this case, the problem is to re-write the Numerology solution to use methods. What is the actual problem? According to the Numerology problem your task is to convert a name into an integer using the pseudo-mathematics of numerology.


What is a Method?

A Method is a section of code which can be referred by name from anywhere in your program, similar to a sub procedure. The structure of an method includes a signature, code, and sometimes a return value. A method's Signature includes the name and input parameters that are passed to the method. Methods benefit the programmer because time is saved from repeating sections of code by simply calling the method's name. Methods can be saved and used in other programs as well. Click here for more information on methods.


Here are some general rules you can follow when using methods:

  • Method name should be meaningful, usually a verb describing the method's function.
  • Each method should have one purpose.
  • The length of the method is no longer than 100 lines or the size of your display.


Step 2: Summarize the Problem into Sections.

Most COMP 1010 assignments divide the problem into sections for you. Although, as you advance to 2nd or 3rd year, you need to determine this step on your own. These sections are a good place start when deciding what methods you need.


Here is an overview of the problem:

  • Prompt the user for a name.
  • Calculate a running sum based on the letters in the name and the values assigned to the letters.
  • Collapse the sum into a destiny number.
  • Assign and display characteristics to the name based on the destiny number


As you can see, I bolded certain words within the list. These words can be used to name the methods we need.


Step 3: Determine the Logic for the Solution

The goal in this step is to determine how each task or method will execute. We need to figure out what the logic, the input parameters, the return values required for each method. A good way to layout the logic is to write pseudocode. Pseudocode a way to explain how an algorithm executes using plain English structured similar to code. We will go through each method, ending with the main() method.


Prompt a User for a Name

Numerology Calc.png


We will not worry about writing our own method for reading input. The JOptionPane.showInputDialog() method will do the work for us. This method displays a form, similar to the above image, which prompts the user for input. The return value is a String object which is similar to an array of characters. For more information on JOptionPane click here.

Remember to import the library javax.swing at the top of the file. More information can be found here.


Calculate a Running Sum From the Name String

This step requires you to take each value assigned to each letter, from the following table, and add the value to a variable storing the sum. You will need the name string as the input parameter and the sum integer as the return value. To process each letter we need to use a loop structure such as the While or For loop. Since we can get the length by calling the Length() in the name String a For loop will do. Each letter must now be compared with all the letters in the table. The pseudocode below will explain how this works.


123456789
ABCDEFGHI
JKKMNOPQR
STUVWXYZ


Pseudocode

CaculateString(name)
{
	For all the characters in the name
	{
		if current char is A or J or S then
			add 1 to sum
                else if current char is B or K or S then
			add 2 to sum.
                      .
                      .
                      .
                else if current char is I or R then
                	add 9 to sum.
        }
	return sum
}


Collapse the Sum into a Destiny Number

You need to add all digits in the sum until it forms a single digit number. To accomplish this, we will use division and mod operators to process each digit untill there are no more digits to process. If you did not know, dividing an Integer by 10 removes that last digit on the right. If you mod an integer by 10 the result is the last digit on the right. For example, the statement 124 / 10 = 12.4 but, since all numbers are integers the result will equal to 12 instead of 12.4. At the same time 124 mod 10 = 4. The following pseudocode will explain further.


Input parameter needed for this method is the sum, and the return value is the destiny number.


There is still a problem with this solution. There are instances where collapsing the integer once will return a number greater than nine. In which case, we need to call this method again until the resulting number is no greater than nine. We will do this in the main() method.


Pseudocode

collapseInteger(sum)
{
	while remaining digits is greater than zero
	{
		result = result plus remaining digits mod 10
		remaining digits = remaining digits / by 10	
	}
	return result
}


Assign Characteristics to the Name

We simply compare the calculated destiny number to a set of destiny numbers. If the comparison is true assign the characteristic to the name and destiny number. Since there will be no more processing after this we can simply display the characteristic to the requesting user. The signature for this method will contain the destiny number. This method will not return anything. The following table displays the characteristics that correspond to a destiny number.


Destiny NumberCharacteristics
1ambitious, independent, and self-sufficient
2supportive, diplomatic, and analytical
3enthusiastic, optimistic, and fun-loving
4practical, traditional, and serious
5adventurous, mercurial, and sensual
6responsible, careful, and domestic
7spiritual, eccentric, and a bit of a loner
8money-oriented, decisive, and stern
9multi-talented, compassionate, and global


Pseudocode

printMessage(destiny number) 
{
	if destiny number is 1 then
		display "1) ambitious, independent, and self-sufficient"
        else if destiny number is 2 then
 		display "2) supportive, diplomatic, and analytical"
		.
		.
		.
	else if destiny number is 9 Then	
		display "9) is multi-talented, compassionate, and global"
}


The Main Method

Lastly, the main method will call the rest of the methods so that other methods to execute the heavy processing for the problem. Additionally, the main method will store all variables for each method's signature. This is the only way to move the data between the methods.


Pseudocode

main(args)
{
 	declare a name string 	  
	declare a sum integer
 	declare a destinyNum integer

        name is entered by user

        sum is calculated by calculateString()

        destiny is calculated by collapseInt()

        while destiny is greater than 10
        	destiny is calculated by collapseInt()
}


Step 4: Organize The Code.

Since all of our methods are defined, we are now ready to edit the java file. Let us open up a text editor and start by entering the class name. We can use "A3Q1" as our class name.


Code

import javax.swing.*;

public class A3Q1
{

}


Note: I imported javax.swing.* because we need it to call the JOptionPane.showInputDialog()method.


Another good practice is to insert constants after the class name. This way you do not need to hunt for them later down the code if you need to change their values. This time we will not do this.


Personally I prefer, but not always possible, is to organize my methods by the order they are used. For example, I comment the names or descriptions of each methods in order from top to bottom and lastly the "main()" method. It is always good to comment your code because commenting allows code to be easily read by other programmers.


Code

import javax.swing.*;

public class A3Q1
{
	// calculate the sum of all characters in the user's name.

        // collapse he sum into the destiny number.

        // display destiny message

        // main
}

Step 5: Type The Rest Of The Code

The Main Method

We will start in the main method because it calls the rest of the methods. First we will declare our variables listed in our pseudocode, followed by the method calls. The methods calls will be commented out until the methods are needed.


Code

public class A3Q1
{
                .
                .
                .
        // main method
	public static void main(String [] args)
	{
		// declare and initialize variables
		String 	name 	= "";
		int	Sum		= 0;
		int     destiny 	= 0;

		// read in user's name as a string
		name = JOptionPane.showInputDialog("Please enter your name.");		

		// calculate sum from name
		//sum = calculateSumFrName(name);

		// collapse sum into destiny number
		//destiny = collapseInt(sum);
		//while(destiny >= 10)
			//destiny = collapseInt(destiny);
		
		// display destiny message
		//displayDestiny(name,destiny);
	}



Remember to initialize each variable you declare at the start of a method. The point is if variable is not set you will get an error if you try to use it. For example, if you declare an Integer datatype, set it to zero. If you declare a String, set it to the space character.

Another helpful suggestion is to test each method once they are completed. This will speed the process of locating errors in your code. One method of testing is to print each method's return value by inserting System.out.println() after each method call. Compile your code and run it each time you complete a method. This is not the best technique for locating errors, but it will work for now.


As I said above the JOptionPane.showInputDialog() is used to get input from the user. Since its a working method there is no need to comment it out.


The CalculateString Method

Now we are ready to code the rest of the methods. Let us move on with the calculateString() method. If we follow pseudocode we get:


Code

public class A3Q1
{        
		.
		.
		.
	// calculate the sum of all characters in the user's name.
	public static int calculateString(String origName)
	{
		String 	upperName 	= origName.toUpperCase();
		int 	sum			= 0;
		char	curr			= ' ';

		for (int r = 0; r < upperName.length(); r++)
		{
			curr = upperName.charAt(r);

			if (curr == 'A' || curr == 'J' || curr == 'S')
				sum += 1;
			else if (curr == 'B' || curr == 'K' || curr == 'T')
				sum += 2;
			else if (curr == 'C' || curr == 'L' || curr == 'U')
				sum += 3;
			else if (curr == 'D' || curr == 'M' || curr == 'V')
				sum += 4;
			else if (curr == 'E' || curr == 'N' || curr == 'W')
				sum += 5;
			else if (curr == 'F' || curr == 'O' || curr == 'X')
				sum += 6;
			else if (curr == 'G' || curr == 'P' || curr == 'Y')
				sum += 7;
			else if (curr == 'H' || curr == 'Q' || curr == 'Z')
				sum += 8;
			else if (curr == 'I' || curr == 'R')
				sum += 9;
		}
	}
		.
		.
		.
}


The collapseInt Method

Once again if we follow the psuedocode we get the following.


Code

public class A3Q1
{        
		.
		.
		.
        // collapse sum into destiny number
	public static int collapseInt(int origNum)
	{
		int result = 0;
		int remaining = origNum;

		while(remaining > 0)
		{
			result += remaining % 10;
			remaining /= 10;
		}

		return(result);
	}
		.
		.
		.
}


The PrintMessage Method

Lastly, the pseudocode for the printMessage method gives us the followling code.


Code

public class A3Q1
{        
		.
		.
		.

    // display destiny message
    public static void printMessage(String name,int destiny)
    {
	    if(destiny == 1)
	            System.out.println(name + " (1) is ambitious, independent, and self-sufficient.");

	    else if(destiny == 2)
	            System.out.println(name + " (2) is supportive, diplomatic, and analytica.");

	    else if(destiny == 3)
	            System.out.println(name + " (3) is enthusiastic, optimistic, and fun-lovin.");

    	    else if(destiny == 4)
	            System.out.println(name + " (4) is practical, traditional, and serious.");

	    else if(destiny == 5)
	            System.out.println(name + " (5) is adventurous, mercurial, and sensual.");

	    else if(destiny == 6)
	            System.out.println(name + " (6) is responsible, careful, and domestic.");

	    else if(destiny == 7)
	            System.out.println(name + " (7) is spiritual, eccentric, and a bit of a loner.");

	    else if(destiny == 8)
	            System.out.println(name + " (8) is money-oriented, decisive, and stern.");

	    else if(destiny == 9)
	            System.out.println(name + " (9) is multi-talented, compassionate, and global.";

	    else
	            System.out.println(name + " (?) is nothing.");
    }
		.
		.
		.
}

Code

Solution Code

Back to the Case Studies homepage