Difference between revisions of "Numerology"

From CompSciWiki
Jump to: navigation, search
m
 
(24 intermediate revisions by 3 users not shown)
Line 31: Line 31:
 
</table>
 
</table>
 
</div>
 
</div>
<br>
+
<br />
 
</p>
 
</p>
 
<p>
 
<p>
Line 61: Line 61:
 
----
 
----
  
'''Submit'''<br />
+
'''Generate''' output from one run of your program where the name is:
1.) your source code<br />
+
2.) output from one run of your program where the name is:
+
 
:# John von Neumann  
 
:# John von Neumann  
 
:# Edsger Dijkstra
 
:# Edsger Dijkstra
Line 71: Line 69:
 
|Solution=
 
|Solution=
 
==How to Approach the Problem==
 
==How to Approach the Problem==
There is a proper series of steps to follow before actually writing the code to create the conversion program. Some questions to think about for coming up with a correct solution to the program are:
+
There is a proper series of steps to follow before actually writing the code to create the conversion program. Thinking about each step in the [[Numerology#Problem|problem]] and how it can be solved before writing the code will lead to cleaner, and more efficient code; not to mention that it follows proper coding standards. Some questions to think about for coming up with a solution to this specific problem are:
  
:*'''How many methods and variables are required?'''
+
:*'''What procedure needs to be followed to implement the program correctly?'''
::-Should everything go in the main method or should it be broken down into multiple methods and code blocks for readability and reuse?
+
::-What type of variables are needed and what should they be initialized to?
::-What type of variables are needed and what should they be initialized too?
+
:*'''What parameters do I need to pass to the methods, and should there be a return value?'''
+
::-What variables are needed from outside the method that should not be passed globally?
+
::-What variable from inside the method is manipulated and needed by other methods?
+
 
:*'''Where should loops and conditional statements be used?'''
 
:*'''Where should loops and conditional statements be used?'''
::-Where does it make sense to use if/else if/else, for and while within the program??
+
::-Where does it make sense to use [[Variables and Literals#Reserved Words|reserved words]] like [[The If-Else Statement#Introduction|if/else]], [[For Loops#Structured Loops|for]] and [[While Loops#Uses|while]] within the program?
 
:*'''When should the code be commented and what should it include?'''
 
:*'''When should the code be commented and what should it include?'''
::-Should documentation be performed before, during or after I have written the program?
+
::-Should [[Comments#Introduction|comments]] and documentation be performed before, during or after I have written the program?
 
<br />
 
<br />
'''Make sure your code complies with the [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 coding standards].''' Following proper coding standards allows for an easier understanding of your code and the future as well as the present. Remember markers as well as other programmers may have to modify or understand your methods in the future. The more practice you have in proper documentation and code syntax, the easier it will be in the future to follow your company's required coding guidelines:
+
'''Make sure your code complies with the [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 coding standards].''' Following proper coding standards allows for an easier understanding of your code in the future as well as the present. Remember markers for assignments as well as other programmers may have to modify or understand your code in the future. The more practice you have in proper documentation and code syntax, the easier it will be in the future to follow any required coding guidelines in the workplace.
  
===Standard Method Separation===
+
===Correct Solution Procedure===
As a rule of thumb, [[Your First Java Program#Methods and the Main Method|methods]] should generally not be longer then the screen width (40-50 lines). Separate methods are used when a protocol of steps or an algorithm will be used repetitively, or serves a different purpose then the current method. Remember, programmers are lazy and never want to have to write duplicate code. After reading this particular problem we can break down the protocol into a couple of simple methods. The protocol for this problem can be broken up as follows:
+
To correctly implement the procedure for this program there are a couple of things to think about. You do not want to have code scattered all over the program randomly to magically produce the correct output. Instead, you want to break the code up into smaller sections to easily distinguish what is happening and where. In a few lectures, if not already, you will learn that Java makes use of [[Overview#What is a User-Defined Method?|user-defined methods]] that set a template for coding in small simple sections. If you know how to use [[Your First Java Program#Methods and the Main Method|methods]] properly already, try approaching this problem using the[[Numerology with Methods| Numerology with Methods]] Case Study. If not, you are in good company and you can write all the code in the [[Your First Java Program#The Main Method|main method]] for this exercise. Methods take a bit of practice and understanding  on why they are used, but they are very effective and general good practice in the programming world. Methods are frequently used in programming languages when:
:# Create a input dialog box and prompt the user for a name to be converted.
+
:*A protocol of steps or an algorithm will be used repetitively
:#Calculate the running sum of the name by converting each character value into it's corresponding numeric value.
+
:*The code section serves a different purpose than the current method/code block
:#Calculate the collapsed digit from the total of the running sum.
+
 
:#Using the collapsed digit, print the destiny number and associated characteristics to output.
+
<br>
 +
Remember, programmers are lazy and never want rewrite the same code, so methods are an ideal solution.  
 
<br />
 
<br />
From the protocol steps it is apparent that there are (at least) four appropriate methods needed to properly implement the problem.
+
For this [[Numerology#Problem|problem]] we will break the code up into sections which will make it easier to follow what is happening and why.  This problem can be broken up as follows:
:*A [[Your First Java Program#The Main Method|main method]] to prompt the user for a name as well as call the other methods appropriately.
+
:#Create an input dialog box and prompt the user for a name to be converted
:*A method to convert each letter from the name into a corresponding number and calculate the running sum.
+
:#Calculate the running sum of the name by converting each character value into its corresponding numeric value
:*A method to calculate the collapsed digit from the total running sum.
+
:#Calculate the collapsed digit from the total of the running sum
:*A method to print the name's destiny number and associated characteristics.
+
:#Using the collapsed digit, print the destiny number and associated characteristics to output
 
+
<br />
===Efficient Parameters and Return Values===
+
From the procedure of steps, it is apparent that there are (at least) four appropriate code sections needed to properly implement the problem.
'''Parameters''' are a tricky concept to understand at first. The correct number of parameters as well as what needs to be a parameter can determine a properly implemented method from a poor one. The idea with parameters is that you want to pass only variables need by the method, and no more! At the same time a variable that is not passed and should have been, can create an incorrect result or a poorly implemented method (which falls under bad coding standards). Remember that global variables should only be used in rare cases. Making all your variables global and having no parameters for any methods is not a good approach to any programming problem.
+
:*A starting section to initialize variables and prompt the user for a name
 
+
:*A section to convert each letter from the name into a corresponding number and calculate the running sum
'''Return Values''' are used to return a variable value that has been (most likely) manipulated inside the method. Java only allows for at most one value to be returned for each method so take this into consideration when creating methods. Methods with too much variable manipulation and functionality can usually be broken down into smaller simpler methods that allows for better readability and usability. Void methods have no return value and for this reason referred to as procedures which perform some functionality but usually do not manipulate variables. Void methods can still use parameters if required (and usually do). An example of a void method would be to print a specific message from a list to output depending on the parameter values passed in.
+
:*A section to calculate the collapsed digit from the total running sum
Eg. a name and corresponding message from their destiny number.
+
:*A finishing section to print the name's destiny number and associated characteristics
  
 
===Consistent use of Loops and Conditional Statements===
 
===Consistent use of Loops and Conditional Statements===
Loops and conditional statements should be used throughout the program as extensively as possible. There use is essential to the general usability of any programming language. Without these statements it would be very difficult to perform some of the simple functionality we take advantage of them for. More exclusively:
+
Loops and conditional statements should be used throughout the program as extensively as possible. Their use is essential to the general usability of any programming language. Without these statements it would be very difficult to perform some of the simple functionality we take advantage of them for. More specifically:
:*[[For Loops#Structured Loops|For loops]] should be used anywhere the number of looping cycles is known.
+
:*[[For Loops#Structured Loops|For loops]] should be used anywhere the number of looping cycles is known
::Eg: Converting each character of a name (where the length is known) to its corresponding digit.
+
::Eg: Converting each character of a name (where the length is known) to its corresponding digit
:*[[While Loops#Uses|While loops]] should be used where the number of looping cycles in unknown and only stops when condition is met.
+
:*[[While Loops#Uses|While loops]] should be used where the number of looping cycles is unknown and only stops when the condition(s) are met
::Eg: Adding each digit of the collapsing sum (which is on an unknown length) to discover its destiny number.
+
::Eg: Adding each digit of the collapsing sum (which is of an unknown length) to discover its destiny number
:*[[The If-Else Statement#Introduction|If/else]] and [[The If-Else Statement#If-Else Ladders|else if]] statements should be used where there is a number of potential solutions and only one is met depending on the variables value.
+
:*[[The If-Else Statement#Introduction|If/else]] and [[The If-Else Statement#If-Else Ladders|else if]] statements should be used where there is a number of potential options and only one is met depending on the variable's value
::Eg: Depending on a characters value/letter a numeric value is associated with it.
+
::Eg: Depending on a characters value/letter, there is a corresponding numeric value  
  
 
===Proper Documentation===
 
===Proper Documentation===
As unenjoyable as it can be, good documentation of your code is very important. Documentation and [[Comments#Introduction|commenting]] may seem unnecessary as the program is very simple and the code is readable, but that is not the point. By applying documentation to all code, whether it be Microsoft Office or a simple numerology program the purpose is still the same; a quick understanding of each methods purpose, what it does and how it is used, as well as its parameters and return variable.
+
As unpleasant as it may be, good code documentation is very important. Your [[Comments#Introduction|comments]] should be written as you create the code so you can use them as a guideline for writing the section properly. Each method should include it's purpose, type of parameters and why they are needed, as well as the return value if there is one. Documentation may seem unnecessary as the current programs are very simple, small, and the code itself is readable. By applying documentation and comments to all code, whether it be Microsoft Office or a simple numerology program, the purpose is still the same; a quick understanding of each code block. Even working through long sections of code, anywhere the code is not clear as to its purpose, comment the code block so it is easy to follow and there is no confusion.
  
  
===Separate the Statements===
+
==Creating the Code in Sections==
The code file contains more than one [[Your First Java Program#Statements|statements]] on each line.
+
After understanding how to approach the [[Numerology#Problem|problem]], you are ready to start building the program. As recommended in the [[Numerology#Solution Procedure|Solution Procedure]] the program and explanation will be broken down into four sections. For each section [http://en.wikipedia.org/wiki/Pseudocode pseudocode] will be provided so an understanding of what has to be done can be grasped, without directly giving you the code. Where's the fun in that?
<pre>
+
int digit1 = (isbn % 10);int total = digit1 * 9;isbn = isbn / 10;
+
int digit2 = (isbn % 10);total = total + digit2 * 8;isbn = isbn / 10;
+
</pre>
+
Each of the above lines of code performs a similar function. Each line can be interpretted as a block of code. By placing each [[Your First Java Program#Statements|statements]] on a separate line and grouping the statements into appropriate code blocks, the result should look something like the following:
+
<pre>
+
int digit1 = (isbn % 10);
+
int total = digit1 * 9;
+
isbn = isbn / 10;
+
int digit2 = (isbn % 10);
+
total = total + digit2 * 8;
+
isbn = isbn / 10;
+
</pre>
+
By placing each of the [[Your First Java Program#Statements|statements]] on a separate line, the readability of the code increases dramatically.  
+
  
===Separate Statements into Code Blocks===
+
===Variable Initialization and User Input===
 +
The [[Your First Java Program#The Main Method|main method]] is the engine of the program. As proper procedure, you should always create and initalize variables at the beginning of a class. The problem states you will need to use [[Input using JOptionPane#Introduction|JOptionPane]] to prompt the user for a name. Remember that this also means that the [[Output using JOptionPane#Don't forget the import statement|swing package import statement]] must be provided before the class, but within the file.
  
Once the [[Your First Java Program#Statements|statements]] are readable, the next step would be to organize them into code blocks as stated in [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards]. Continuing with our previous example, the functionality of the code can be broken into two distinct code blocks.
 
 
<pre>
 
<pre>
int digit1 = (isbn % 10);
+
import javax.swing.*;//import JOptionPane package
int total = digit1 * 9;
+
isbn = isbn / 10;
+
  
int digit2 = (isbn % 10);
+
public class numerologyProblem{
total = total + digit2 * 8;
+
isbn = isbn / 10;
+
</pre>
+
Almost each line of code in the messy code file can be considered a separate code block. Take the time to read the code and understand how everything works together before deciding which [[Your First Java Program#Statements|statements]] should be grouped together.
+
  
One of the code blocks that should be added is a variable declaration code block at the beginning of [[Your First Java Program#The Main Method|the main method]]. Throughout the [[Case Study I#Code|messy code]], integers are declared. All of the [[Variables and Literals#Variables|declaration statements]] should be placed at the beginning of [[Your First Java Program#The Main Method|the main method]] to ensure the code stays organized. Going to the previous example, two [[Variables and Literals#Variables|declaration statements]] can be moved to the top as depicted below.
+
    public static void main (String[] args){
<pre>
+
       
int digit1;
+
        //VARIABLE CREATION AND INITIALIZATION
int digit2;
+
       
 +
        String name = NULL; //variable to hold the name we are going to prompt the user for
 +
        String nameAllCaps = NULL; //name after it has been converted to all caps
 +
        char ch = NULL;//the letter peeled off the name that is to be converted to a numeric value
 +
        int sum = 0;//sum of the converted name
 +
        int sumDigits = 0;//sum of the digits from the converted name
 +
        boolean doneFindingSumDigits = false;//needed for a while loop to collapse the sum until we have the destiny number
  
digit1 = (isbn % 10);
+
        //name = result from the users input (using JOptionPane Prompt)
int total = digit1 * 9;
+
isbn = isbn / 10;
+
  
digit2 = (isbn % 10);
 
total = total + digit2 * 8;
 
isbn = isbn / 10;
 
 
</pre>
 
</pre>
  
===Add Comments to Explain the Code===
+
===Converting Characters Into Their Corresponding Numbers===
The [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 coding standards], or the Funky Books Inc. coding standards, make numerous points concerning [[Comments|comments]] in code. To be specific, statements 1, 2, 4, and 7 can be applied to the code file for this [[Case Study I|case study]]. All major code blocks should be identified by now. Look over each code block and briefly explain what it does in a comment. Since all [[Variables and Literals#Variables|declaration statements]] have been moved to the top of the [[Your First Java Program#The Main Method|the main method]] , make sure to apply coding standard 7 from the [http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards].
+
You need to peel apart the name string and convert each character into a number to be added to the running sum. The use of a [[For Loops#Structured Loops|for loop]] makes sense to compare each character of the known [[Strings#length|length]] name with the chart of values to find its corresponding numerical value. For the conversion of a character to a numerical value you should be thinking of using conditional statements like [[The If-Else Statement#Introduction|if]] and [[The If-Else Statement#If-Else Ladders|else if]] for each letter in the alphabet. If the character matches the letter, the corresponding numerical value should be added onto the running sum. After the entire name has been converted, you have the total running sum value which will be collapsed to calculate the destiny number. To avoid extra work, before using any comparing conditional statements convert the name to either upper case or lower case letters so only half the conditional checks are needed.
 
+
==Optimize the Code by Removing Unnecessary Variables==
+
At the top of [[Your First Java Program#The Main Method|the main method]], there should now be a number of [[Variables and Literals#Variables|variables]]  
+
declared. Notice that there are nine different "digit" [[Variables and Literals#Variables|variables]] which are only used once to store the same calculation.  
+
  
 
<pre>
 
<pre>
int digit1;
 
int digit2;
 
  
digit1 = (isbn % 10);
+
        //nameAllCaps = (name converted to all caps)
int total = digit1 * 9;
+
isbn = isbn / 10;
+
  
digit2 = (isbn % 10);
+
        /*for(int i = 0; i < length of the name; i++){
total = total + digit2 * 8;
+
              ch = nameAllCaps.charAt(i);
isbn = isbn / 10;
+
              if (ch = A or J or S){
 +
                  sum = sum + 1;//the value corresponding with the three conditional values
 +
              }
 +
              else if (ch = B or K or T){
 +
                  sum = sum + 2;
 +
              }
 +
           
 +
              //... etc. for all of the tables conversion values ...
 +
         
 +
        }*///end for loop
 
</pre>
 
</pre>
The code sample from above shows two of the nine digit [[Variables and Literals#Variables|variables]]. These two [[Variables and Literals#Variables|variables]] can be replaced with a single one as follows:
 
<pre>
 
int digit;
 
  
digit = (isbn % 10);
+
===Calculate the Destiny Number===
int total = digit * 9;
+
With an unknown valued (as well as unknown length) sum you need to calculate the destiny number. A recommended procedure to do this is to add the last digit from the total sum to a "sum of digits" variable, and then remove the last digit from the total sum. Repeat this process until the sum is a valid destiny number. To follow this procedure the use of the [[Arithmetic Operators|division operator]] as well as the [[Arithmetic Operators|remainder operator]] (mod) is required, so a good understanding of how they work is strongly advised.
isbn = isbn / 10;
+
 
+
digit = (isbn % 10);
+
total = total + digit * 8;
+
isbn = isbn / 10;
+
</pre>
+
  
==Fix the Errors in the Code==
 
The [[Case Study I#Code|messy code]] contained a total of eight different coding errors. Each error presented in this section is ordered as it appears in the [[Case Study I#Code|code]] from the [[Case Study I|case study]].
 
===Error One===
 
 
<pre>
 
<pre>
String temp = JOptionPane.showInputDialog("")
+
</pre>
+
        while(!doneFindingSumDigits){
Technically, the above code does not break the functionality of the application as the method call still makes the [[Input using JOptionPane#Input Dialog|input dialog]] appear to take input from the user. Although, from a usability standpoint the code does cause an error. The user who is running the application needs to know what to enter as input into the [[Input using JOptionPane#Input Dialog|input dialog]]. Without a proper message, the user cannot be expected to know what the application is expecting as input. An example of a proper message is as follows:
+
            /*while(currentValue is still a valid positive number){
<pre>
+
                  sumDigits += the last digit from the integer (remainder operation)
temp = JOptionPane.showInputDialog("Enter the first 9 digits of a 10-digit ISBN number.");
+
                  remove the last digit from currentValue (divisor operation)
</pre>
+
            }*/
 +
            //if (the sum is not a valid destiny number){
 +
                sum = sumDigits;  
 +
                sumDigits = 0;
 +
            //}
 +
              else{
 +
                doneFindingSumDigits = true;
 +
              }     
 +
        }//end while loop
  
===Error Two===
 
<pre>
 
int isbn = Temp;
 
</pre>
 
There are two problems with the above code sample. The first problem being that the [[Variables and Literals#Variables|variable]] "Temp" is of type [[Strings|string]] and not of the primitive type [[Common Primitive Variables#Primitive Type int|int]]. The second problem is the name of the [[Variables and Literals#Variables|variable]] "Temp". The [[Variables and Literals#Variables|variable]] was originally declared as "temp" and Java is a [[Your First Java Program#Case Sensitivity|case sensitive]] language. Both programs are repaired by replacing the code with the line below.
 
<pre>
 
isbn = Integer.parseInt(temp);
 
 
</pre>
 
</pre>
  
===Error Three===
+
===Print the Destiny Number and Characteristics===
<pre>
+
Finally, you want to print the name and characteristics of the corresponding destiny number to [[Output using System.out.#Introduction|standard output]]. After this procedure, the program requirements have been completed.
isbn = isbn // 10;
+
Congratulations, you are almost done! Compile and run your program and see if your output matches the sample output below.
</pre>
+
An extra front slash changes the [[Arithmetic Operators|division operation]] into a comment which also comments out the semi-colon required at the end of every [[Your First Java Program#Statements|statement]]. Remove the extra front slash to correct the error.  
+
<pre>
+
isbn = isbn / 10;
+
</pre>
+
  
===Error Four===
 
 
<pre>
 
<pre>
digit = (isbn % 10)
 
</pre>
 
The [[Your First Java Program#Statements|statement]] above is missing the semi-colon at the end of the line. Add the semi-colon to fix the error.
 
<pre>
 
digit = (isbn % 10);
 
</pre>
 
  
===Error Five===
+
        if(sumDigits == 1){
<pre>
+
            //print name and message for (1) characteristics to standard output
total = total + digit + 6;
+
        }
</pre>
+
        else if(sumDigits == 2){
This error is known as a run time error. A run time error does not cause a compilation error, but it causes the program to produce incorrect results. In the explaination of the [[Case Study I#ISBN Check Digit Overview|ISBN check digit]], the sixth ISBN number should be multiplied by six, not added. This error is fixed by changing the second [[Arithmetic Operators|addition]] operation to a [[Arithmetic Operators|multiplication]] operation.
+
            //print name and message for (2) characteristics to standard output
<pre>
+
        }
total = total + digit * 6;
+
</pre>
+
  
===Error Six===
+
        //.... etc. complete for all numbers one through nine ...
<pre>
+
digit = (isbn / 10);
+
</pre>
+
Just like [[#Error Five|error five]], the above [[Your First Java Program#Statements|statement]] causes a run time error. To isolate the last digit in the ISBN number, the ISBN must have the [[Arithmetic Operators|modulus operator]] applied, not the [[Arithmetic Operators|division operator]]. The above statement is fixed by replacing the [[Arithmetic Operators|division operator]] with the [[Arithmetic Operators|modulus operator]].  
+
<pre>
+
digit = (isbn % 10);
+
</pre>
+
  
===Error Seven===
+
    }//end main method
<pre>
+
digit = (isbn * 10);
+
</pre>
+
The above [[Your First Java Program#Statements|statement]] is almost identical to [[#Error Six]]. The [[Arithmetic Operators|multiplication operator]] should be replaced with the [[Arithmetic Operators|modulus operator]].
+
<pre>
+
digit = (isbn % 10);
+
</pre>
+
  
===Error Eight===
+
    return 0;
<pre>
+
}//end class
total = total + digit - 1;
+
</pre>
+
The error in the code above is [[#Error Five|error five]] almost identical to [[#Error Five]]. Replace the [[Arithmetic Operators|subtraction operator]] with the [[Arithmetic Operators|multiplication operator]] to remedy this error.
+
<pre>
+
total = total + digit * 1;
+
 
</pre>
 
</pre>
  
==Add Code to Output Progress Reports as the Program Executes==
+
=Output Solutions=
To add progress reports to the program, three things need to be addressed:
+
Here are the correct answers to the output required from the problem description. Compare these with your outputs to see if you have generated code to solve the exercise. If your output does not match the given solutions and you can see visible discrepancies in the answers, then take a quick look at the sample solution code and see if there is a simple quick fix.
<ul>
+
<li>Where to place the progress reports</li>
+
<li>What progress should be reported</li>
+
<li>Adding the code to report progress</li>
+
</ul>
+
By adding code to report on the status of the application, the user and yourself know what is happening behind the scenes when the program is executing. For a small application like this [[Case Study I|case study]] it may seem trivial. It is a good practice to get into as in larger programs consisting of many files each with many methods, it can be difficult to locate a run-time error in your code if the program does not explicitly say what it is currently doing.
+
  
===Location===
+
1. John von Neumann
By now the code file should be broken up into multiple code blocks, as done [[#Separate the Statements into Code Blocks|earlier in this solution]]. Each code block should represent a major code segment in the program. Each code block can be considered a potential point for a progress report. Read over the code and decide which are vital points in the execution of the program.
+
 
+
===Report Content===
+
The next step is to decide what should be outputted to describe the progress of the program. This output can be the current value of a [[Variables and Literals|variable]], an output statement saying that the program has reached a certain point in the code, or potentially a combination of both. A progress report should output data on the program that is relevant to its execution. For this [[Case Study I|case study]], each calculation performed on the ISBN is vital to determining the check digit, therefore a progress report should output the value of each calculation.
+
 
+
===Adding Output Code===
+
The best way to add output to the program is by adding [[Output using System.out|System.out]] statements to the appropriate code blocks. When adding the code, make sure the message that will be outputted is unique in comparison to the other progress report [[Your First Java Program#Statements|statements]]. Each statement should be unique as they are meant to identify the section of code being executed. If the statements are not unique, then there will be no way of telling which progress report has been outputted. Here is an example of the code before adding a [[Output using System.out|System.out]] statement.
+
 
<pre>
 
<pre>
//isolate last digit and multiply by 9
+
John von Neumann (9) is multi-talented, compassionate, and global.
digit = (isbn % 10);
+
total = digit * 9;
+
isbn = isbn / 10;
+
 
</pre>
 
</pre>
After the output [[Your First Java Program#Statements|statement]] is added, the code will look like the following:
+
2. Edsgter Dijkstra
 
<pre>
 
<pre>
//isolate last digit and multiply by 9
+
Edsgter Dijkstra (8) is money-oriented, decisive, and stern.
digit = (isbn % 10);
+
total = digit * 9;
+
isbn = isbn / 10;
+
System.out.println (digit + " * " + 9 + " for a running total of " + total);
+
 
</pre>
 
</pre>
When the program is executing, the following output will appear in the progress window. The ISBN number used as input for the example below is 1-2345-6789.
+
3. (of your choosing) Blaise Pascal
 
<pre>
 
<pre>
9 * 9 for a running total of 81
+
Blaise Pascal (1) is ambitious, independent, and self-sufficient.
 
</pre>
 
</pre>
Now the you will know what part of the code is being executed along with the status of the current calculation.
 
  
Remember that this is not the only "correct" progress report. There can be many different progress reports based on how the vital points of the program were interpreted. Although, in this [[Case Study I|case study]] the calculations are exceptionally important points to the correct execution of the program.
+
=Sample Solution=
 +
Remember, this is not the only "correct" coding solution to the problem. This is only one of many proper ways to implement the problem with your basic understanding of Java. There can be many different correct solutions based on how the vital points of the program were interpreted and coded.
 +
 
 +
<br />
 +
'''After you have completely finished writing and testing your code''' I recommend taking a glance at the sample solution. Comparing similarities and differences between your code will let you know what is a good practice from what is a bad habit.
  
 
|SolutionCode=
 
|SolutionCode=
 +
 
import javax.swing.*;
 
import javax.swing.*;
import java.util.Date;
 
  
 
/**
 
/**
* calculate a check digit for ISBNs
+
* numberology_solution.java
*
+
*
* @author:    1010 Instructors
+
* COMP 1010 SECTION Axx
* @version:   2007-September
+
* INSTRUCTOR Name of your instructor
*/
+
* ASSIGNMENT Assignment #, question #
 +
* @author
 +
* @version
 +
*
 +
* PURPOSE: Determines a destiny number and characteristics given a name.
 +
*/
  
public class CaseStudy1_ISBN_Solution
+
public class numerologySolution {
{
+
public static void main (String[] args) {
    /**
+
    * PURPOSE: inputs a 9-digit ISBN, calculates the check digit and outputs a 10-digit ISBN
+
    */
+
    public static void main (String [] args)  
+
    {
+
  
        //variables declared here
+
String name, origName;
        String temp;         //temporary input string
+
char    ch;
        int isbn;           //9-digit ISBN
+
int     sum = 0;
        int digit;           //isolated ISBN digit
+
int     sumDigits = 0;
        int total;           //total of isbn number when each digit is multiplied by check value
+
boolean doneFindingSumDigits = false;//finding sum digits cannot be done because it has not started yet
        int checkDigit;     //value of total%11(as per ISBN standard)
+
  
        //get input
+
origName = JOptionPane.showInputDialog ("Numerology Calculator -"
        temp = JOptionPane.showInputDialog
+
                                        + '\n' + "Enter a name"); // Create the GUI to request the user for a name
        ("Enter the first 9 digits of a 10-digit ISBN number.");
+
        isbn = Integer.parseInt(temp);
+
  
        //confirm input
+
//convert the name to all upper-case letters so that we don't have to compare both upper-case and lower case
        System.out.println ("You have entered " + temp + ".\n\nThe weighted value of the ISBN is:");
+
name = origName.toUpperCase();
  
        //isolate last digit and multiply by 9
+
for (int i=0; i<name.length(); i++) {  //for each letter in the name
        digit = (isbn % 10);
+
ch = name.charAt(i);                //get the character in the next position and find its numeric value
        total = digit * 9;
+
if (ch=='A' {{!}}{{!}} ch=='J' {{!}}{{!}} ch=='S')
        isbn = isbn / 10;
+
sum = sum + 1;                  //if the character is a A, J or S add one to the running value
        System.out.println (digit + " * " + 9 + " for a running total of " + total);
+
else
 +
if (ch=='B' {{!}}{{!}} ch=='K' {{!}}{{!}} ch=='T')
 +
sum = sum + 2;
 +
else
 +
if (ch=='C' {{!}}{{!}} ch=='L' {{!}}{{!}} ch=='U')
 +
sum = sum + 3;
 +
else
 +
if (ch=='D' {{!}}{{!}} ch=='M' {{!}}{{!}} ch=='V')
 +
sum = sum + 4;
 +
else
 +
if (ch=='E' {{!}}{{!}} ch=='N' {{!}}{{!}} ch=='W')
 +
sum = sum + 5;
 +
else
 +
if (ch=='F' {{!}}{{!}} ch=='O' {{!}}{{!}} ch=='X')
 +
sum = sum + 6;
 +
else
 +
if (ch=='G' {{!}}{{!}} ch=='P' {{!}}{{!}} ch=='Y')
 +
sum = sum + 7;
 +
else
 +
if (ch=='H' {{!}}{{!}} ch=='Q' {{!}}{{!}} ch=='Z')
 +
sum = sum + 8;
 +
else
 +
if (ch=='I' {{!}}{{!}} ch=='R')
 +
sum = sum + 9;
 +
}
  
        //isolate next digit and multiply by 8
+
// find sum of the digits ... and "continue" to find sum of the
        digit = (isbn % 10);
+
// digits until sum is between 1 and 9
        total = total + digit * 8;
+
        isbn = isbn / 10;
+
        System.out.println (digit + " * " + 8 + " for a running total of " + total);
+
  
        //isolate next digit and multiply by 7
+
while (!doneFindingSumDigits) {
        digit = (isbn % 10);
+
while (sum > 0) {
        total = total + digit * 7;
+
sumDigits = sumDigits + sum%10; //add the value of the last digit to total sum of the digits
        isbn = isbn / 10;
+
sum = sum / 10; //remove the last digit which was just added to the sum of the digits
        System.out.println (digit + " * " + 7 + " for a running total of " + total);
+
}
 +
if (sumDigits > 9) {//if the sum of the digits is within the destiny number range your done
 +
sum = sumDigits;
 +
sumDigits = 0;
 +
}
 +
else
 +
doneFindingSumDigits = true;
 +
}
 +
//find the characteristic message associated with the destiny number
 +
if (sumDigits == 1)
 +
System.out.println (origName + " (1) " +
 +
  "is ambitious, independent, and self-sufficient.");
 +
else
 +
if (sumDigits == 2)
 +
System.out.println (origName + " (2) " +
 +
  "is supportive, diplomatic, and analytical.");
 +
else
 +
if (sumDigits == 3)
 +
System.out.println (origName + " (3) " +
 +
  "is enthusiastic, optimistic, and fun-loving.");
 +
else
 +
if (sumDigits == 4)
 +
System.out.println (origName + " (4) " +
 +
  "is enthusiastic, optimistic, and fun-loving.");
 +
else
 +
if (sumDigits == 5)
 +
System.out.println (origName + " (5) " +
 +
  "is adventurous, mercurial, and sensual.");
 +
else
 +
if (sumDigits == 6)
 +
System.out.println (origName + " (6) " +
 +
  "is responsible, careful, and domestic.");
 +
else
 +
if (sumDigits == 7)
 +
System.out.println (origName + " (7) " +
 +
  "is spiritual, eccentric, and a bit of a loner.");
 +
else
 +
if (sumDigits == 8)
 +
System.out.println (origName + " (8) " +
 +
  "is money-oriented, decisive, and stern.");
 +
else
 +
if (sumDigits == 9)
 +
System.out.println (origName + " (9) " +
 +
  "is multi-talented, compassionate, and global.");
 +
}
 +
}
  
        //isolate next digit and multiply by 6
 
        digit = (isbn % 10);
 
        total = total + digit * 6;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 6 + " for a running total of " + total);
 
  
        //isolate next digit and multiply by 5
 
        digit = (isbn % 10);
 
        total = total + digit * 5;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 5 + " for a running total of " + total);
 
 
        //isolate next digit and multiply by 4
 
        digit = (isbn % 10);
 
        total = total + digit * 4;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 4 + " for a running total of " + total);
 
 
        //isolate next digit and multiply by 3
 
        digit = (isbn % 10);
 
        total = total + digit * 3;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 3 + " for a running total of " + total);
 
 
        //isolate next digit and multiply by 2
 
        digit = (isbn % 10);
 
        total = total + digit * 2;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 2 + " for a running total of " + total);
 
 
        //isolate next digit and multiply by 1
 
        digit = (isbn % 10);
 
        total = total + digit * 1;
 
        isbn = isbn / 10;
 
        System.out.println (digit + " * " + 1 + " for a running total of " + total);
 
 
        //calculate check digit
 
        checkDigit = total % 11;
 
 
        //output weighted total and check digit
 
        System.out.println ("The weighted total is: " + total +
 
                            "\nThe check digit is : " + checkDigit +
 
                            "\n\nThe 10-digit ISBN is: " + temp + checkDigit);
 
 
        System.out.println("\nProgrammed by COMP 1010 Instructors");
 
        System.out.println("Date: " + new Date());
 
        System.out.println ("*** End of Processing ***");
 
 
    }//end main
 
}//end class
 
 
|SideSectionTitle=Intro to Numerology
 
|SideSectionTitle=Intro to Numerology
 
|SideSection=
 
|SideSection=
KYLE PICTURE
+
[[Image:Number2_casestudy.jpg|center]]<BR>
<BR>
+
 
 
}}
 
}}

Latest revision as of 23:50, 5 April 2011

Back to the Case Studies homepage

Problem

Write a complete Java program that will convert a name into an integer using the pseudo-mathematics (otherwise known as “malarkey”) of numerology. This is just an introduction on the use of numerology in field of Computer Science. Numerology is most commonly used in Computer Science for cryptography and to implement hashing functions. For good programming practices follow the COMP 1010 coding standards.

Your Java program will prompt a user for a name as follows:

Numerology Calc.png


For each alphabetic character in the name, you will add a value to a running sum based upon the following table:

123456789
ABCDEFGHI
JKLMNOPQR
STUVWXYZ


For example, if the name entered is “Alan Turing”, the running sum would ultimately be equal to:

1 + 3 + 1 + 5 + 2 + 3 + 9 + 9 + 5 + 7 = 45

This sum needs to be “collapsed” by adding all its digits together. Thus 45 becomes 4 + 5 = 9. This collapsing process needs to continue until the final result is a single digit (obviously between 1 and 9). This single digit is known as the “destiny number” and is used to assign certain characteristics to the name as follows:

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

Assuming the input of “Alan Turing”, your program will generate output of:

 Alan Turing (9) is multi-talented, compassionate, and global

Output need only be generated by System.out.


Generate output from one run of your program where the name is:

  1. John von Neumann
  2. Edsger Dijkstra
  3. one of your choosing
 

Intro to Numerology

Number2 casestudy.jpg

Solution

How to Approach the Problem

There is a proper series of steps to follow before actually writing the code to create the conversion program. Thinking about each step in the problem and how it can be solved before writing the code will lead to cleaner, and more efficient code; not to mention that it follows proper coding standards. Some questions to think about for coming up with a solution to this specific problem are:

  • What procedure needs to be followed to implement the program correctly?
-What type of variables are needed and what should they be initialized to?
  • Where should loops and conditional statements be used?
-Where does it make sense to use reserved words like if/else, for and while within the program?
  • When should the code be commented and what should it include?
-Should comments and documentation be performed before, during or after I have written the program?


Make sure your code complies with the COMP 1010 coding standards. Following proper coding standards allows for an easier understanding of your code in the future as well as the present. Remember markers for assignments as well as other programmers may have to modify or understand your code in the future. The more practice you have in proper documentation and code syntax, the easier it will be in the future to follow any required coding guidelines in the workplace.

Correct Solution Procedure

To correctly implement the procedure for this program there are a couple of things to think about. You do not want to have code scattered all over the program randomly to magically produce the correct output. Instead, you want to break the code up into smaller sections to easily distinguish what is happening and where. In a few lectures, if not already, you will learn that Java makes use of user-defined methods that set a template for coding in small simple sections. If you know how to use methods properly already, try approaching this problem using the Numerology with Methods Case Study. If not, you are in good company and you can write all the code in the main method for this exercise. Methods take a bit of practice and understanding on why they are used, but they are very effective and general good practice in the programming world. Methods are frequently used in programming languages when:

  • A protocol of steps or an algorithm will be used repetitively
  • The code section serves a different purpose than the current method/code block


Remember, programmers are lazy and never want rewrite the same code, so methods are an ideal solution.
For this problem we will break the code up into sections which will make it easier to follow what is happening and why. This problem can be broken up as follows:

  1. Create an input dialog box and prompt the user for a name to be converted
  2. Calculate the running sum of the name by converting each character value into its corresponding numeric value
  3. Calculate the collapsed digit from the total of the running sum
  4. Using the collapsed digit, print the destiny number and associated characteristics to output


From the procedure of steps, it is apparent that there are (at least) four appropriate code sections needed to properly implement the problem.

  • A starting section to initialize variables and prompt the user for a name
  • A section to convert each letter from the name into a corresponding number and calculate the running sum
  • A section to calculate the collapsed digit from the total running sum
  • A finishing section to print the name's destiny number and associated characteristics

Consistent use of Loops and Conditional Statements

Loops and conditional statements should be used throughout the program as extensively as possible. Their use is essential to the general usability of any programming language. Without these statements it would be very difficult to perform some of the simple functionality we take advantage of them for. More specifically:

  • For loops should be used anywhere the number of looping cycles is known
Eg: Converting each character of a name (where the length is known) to its corresponding digit
  • While loops should be used where the number of looping cycles is unknown and only stops when the condition(s) are met
Eg: Adding each digit of the collapsing sum (which is of an unknown length) to discover its destiny number
  • If/else and else if statements should be used where there is a number of potential options and only one is met depending on the variable's value
Eg: Depending on a characters value/letter, there is a corresponding numeric value

Proper Documentation

As unpleasant as it may be, good code documentation is very important. Your comments should be written as you create the code so you can use them as a guideline for writing the section properly. Each method should include it's purpose, type of parameters and why they are needed, as well as the return value if there is one. Documentation may seem unnecessary as the current programs are very simple, small, and the code itself is readable. By applying documentation and comments to all code, whether it be Microsoft Office or a simple numerology program, the purpose is still the same; a quick understanding of each code block. Even working through long sections of code, anywhere the code is not clear as to its purpose, comment the code block so it is easy to follow and there is no confusion.


Creating the Code in Sections

After understanding how to approach the problem, you are ready to start building the program. As recommended in the Solution Procedure the program and explanation will be broken down into four sections. For each section pseudocode will be provided so an understanding of what has to be done can be grasped, without directly giving you the code. Where's the fun in that?

Variable Initialization and User Input

The main method is the engine of the program. As proper procedure, you should always create and initalize variables at the beginning of a class. The problem states you will need to use JOptionPane to prompt the user for a name. Remember that this also means that the swing package import statement must be provided before the class, but within the file.

import javax.swing.*;//import JOptionPane package

public class numerologyProblem{

    public static void main (String[] args){
        
        //VARIABLE CREATION AND INITIALIZATION
        
        String name = NULL; //variable to hold the name we are going to prompt the user for
        String nameAllCaps = NULL; //name after it has been converted to all caps
        char ch = NULL;//the letter peeled off the name that is to be converted to a numeric value
        int sum = 0;//sum of the converted name
        int sumDigits = 0;//sum of the digits from the converted name
        boolean doneFindingSumDigits = false;//needed for a while loop to collapse the sum until we have the destiny number

        //name = result from the users input (using JOptionPane Prompt)

Converting Characters Into Their Corresponding Numbers

You need to peel apart the name string and convert each character into a number to be added to the running sum. The use of a for loop makes sense to compare each character of the known length name with the chart of values to find its corresponding numerical value. For the conversion of a character to a numerical value you should be thinking of using conditional statements like if and else if for each letter in the alphabet. If the character matches the letter, the corresponding numerical value should be added onto the running sum. After the entire name has been converted, you have the total running sum value which will be collapsed to calculate the destiny number. To avoid extra work, before using any comparing conditional statements convert the name to either upper case or lower case letters so only half the conditional checks are needed.


        //nameAllCaps = (name converted to all caps)

        /*for(int i = 0; i < length of the name; i++){
               ch = nameAllCaps.charAt(i);
               if (ch = A or J or S){
                   sum = sum + 1;//the value corresponding with the three conditional values
               }
               else if (ch = B or K or T){
                   sum = sum + 2;
               }
            
               //... etc. for all of the tables conversion values ...
          
        }*///end for loop

Calculate the Destiny Number

With an unknown valued (as well as unknown length) sum you need to calculate the destiny number. A recommended procedure to do this is to add the last digit from the total sum to a "sum of digits" variable, and then remove the last digit from the total sum. Repeat this process until the sum is a valid destiny number. To follow this procedure the use of the division operator as well as the remainder operator (mod) is required, so a good understanding of how they work is strongly advised.

 
        while(!doneFindingSumDigits){
            /*while(currentValue is still a valid positive number){
                  sumDigits += the last digit from the integer (remainder operation)
                  remove the last digit from currentValue (divisor operation)
            }*/
            //if (the sum is not a valid destiny number){
                sum = sumDigits; 
                sumDigits = 0;
            //}
              else{
                doneFindingSumDigits = true;
              }       
        }//end while loop

Print the Destiny Number and Characteristics

Finally, you want to print the name and characteristics of the corresponding destiny number to standard output. After this procedure, the program requirements have been completed. Congratulations, you are almost done! Compile and run your program and see if your output matches the sample output below.


        if(sumDigits == 1){
            //print name and message for (1) characteristics to standard output
        }
        else if(sumDigits == 2){
            //print name and message for (2) characteristics to standard output
        }

        //.... etc. complete for all numbers one through nine ...

    }//end main method

    return 0;
}//end class

Output Solutions

Here are the correct answers to the output required from the problem description. Compare these with your outputs to see if you have generated code to solve the exercise. If your output does not match the given solutions and you can see visible discrepancies in the answers, then take a quick look at the sample solution code and see if there is a simple quick fix.

1. John von Neumann

John von Neumann (9) is multi-talented, compassionate, and global.

2. Edsgter Dijkstra

Edsgter Dijkstra (8) is money-oriented, decisive, and stern.

3. (of your choosing) Blaise Pascal

Blaise Pascal (1) is ambitious, independent, and self-sufficient.

Sample Solution

Remember, this is not the only "correct" coding solution to the problem. This is only one of many proper ways to implement the problem with your basic understanding of Java. There can be many different correct solutions based on how the vital points of the program were interpreted and coded.


After you have completely finished writing and testing your code I recommend taking a glance at the sample solution. Comparing similarities and differences between your code will let you know what is a good practice from what is a bad habit.

Code

Solution Code

Back to the Case Studies homepage