Difference between revisions of "Case Study II - Solution"

From CompSciWiki
Jump to: navigation, search
(Deciphering the Pattern)
 
(16 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
{{
 
{{
 
1010Topic
 
1010Topic
|Introduction=Introduction goes here.
+
|Introduction=
 +
<p>
 +
This is the solution page for [[Case Study II]]. Here you will find the sample solution code to the problem, as well as an explanation of how to arrive at this solution. The information required to complete this case study can be found in the chapters previous to this one.
 +
</p>
 +
<p>
 +
The tasks were:
 +
<ul>
 +
<li>Use a loop to minimize repeated code.</li>
 +
<li>Use an if statement to print out check digits of 10 as X.</li>
 +
</ul>
 +
 
 +
|Overview=
 +
We will be using a loop and if statement to create the solution code. You can get more information on these topics at the following links:
 +
<ul>
 +
<li>[[Control Structures|Chapter 5: Control Structures]]</li>
 +
<li>[[Loops|Chapter 6: Loops]]</li>
 +
<li>[[Case Study I#ISBN Check Digit Overview| ISBN Check Digit Overview]]</li>
 +
<li>[http://courses.cs.umanitoba.ca/index.asp?sec=3394&too=30&eve=1&ppa=5178 COMP 1010 Coding Standards]</li>
 +
</ul>
  
|Overview=Overview goes here.
 
  
 
|Chapter_TOC=[[Java Fundamentals]]
 
|Chapter_TOC=[[Java Fundamentals]]
Line 11: Line 28:
 
<br />
 
<br />
  
total = 0; total needs to be initialized before loop
+
=Sample Solution=
 +
This section will explain how to develop the [[Case Study II - Solution#Sample Solution Code|solution]] to the tasks given in [[Case Study II]].
 +
 
 +
=Adding the Loop=
 +
 
 +
Loops are a great way to code algorithms that follow a pattern. They allow you to take code that might have taken hundreds of lines and trim it down to a fraction of the size. You will see the effectiveness of a loop in this case study.
 +
 
 +
==Find the Repetition==
 +
 
 +
The first thing that needs to be done with this code is to look for the repetition. If we intend to add a [[Loops|loop]], we will need to find what will be going into it. Let us take a look.
 +
 
 +
<pre>
 +
        //isolate last digit and multiply by 9
 +
        digit = (isbn % 10);
 +
        total = digit * 9;
 +
        isbn = isbn / 10;
 +
        System.out.println (digit + " * " + 9 + " for a running total of " + total);
 +
 
 +
        //isolate next digit and multiply by 8
 +
        digit = (isbn % 10);
 +
        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
 +
        digit = (isbn % 10);
 +
        total = total + digit * 7;
 +
        isbn = isbn / 10;
 +
        System.out.println (digit + " * " + 7 + " for a running total of " + total);
 +
</pre>
 +
 
 +
Just by looking at the first three sections of code we can already see a pattern. Its easy to see that each section does the same four actions: 1) Isolate the digit. 2) Add digit multiplied by its position to the total. 3) Remove the last digit from the ISBN. 4) Print out the running total.
 +
 
 +
==Deciphering the Pattern==
 +
 
 +
Now that we have found where the repetition is located in the code, we now have to figure out how to make an equation out of it. Lets look at the code for the 8th digit and compare each line to the sections for other digits.
 +
 
 +
<pre>digit = (isbn % 10);</pre>
 +
 
 +
Here we see that this line of code stays the same in every section. So lets look at the next line in a section.
 +
 
 +
<pre>total = total + digit * 8;</pre>
 +
 
 +
We see here that this equation is the same for each section, except for the multiplier. We can see that the number matches which ever digit it currently is. At the beginning it starts as a 9 for the ninth digit, then an 8 for the eighth digit, then all the way to 1 for the first one. The number is decrementing by 1 each section. This will be important to keep in mind when we decipher the pattern. For now lets look at the next line of code.
 +
 
 +
<pre>isbn = isbn / 10;</pre>
 +
 
 +
Again, this code is the same in every section. On to the section's last line of code.
 +
 
 +
<pre>System.out.println (digit + " * " + 8 + " for a running total of " + total);</pre>
 +
 
 +
Here we have another example where all the code stays the same except for the value of the multiplier, which happens to be the same value as the number that changed in the previous example. This number will decrement by 1 for each section of code.
 +
 
 +
==Creating the Pattern==
 +
 
 +
What we just learned from the previous section is that there is a number, we will call it the 'multiplier digit', that decrements by one every section of code. Lets treat that number as a variable, i. In the first section i = 9, the second section i = 8, the third i = 7, and so on until i = 1.
 +
 
 +
So what do know about the 'multiplier digit'?
 +
    - We know it starts at 9. (i = 9)
 +
    - It decrements down until it reaches 1, then it stops. (i > 0)
 +
    - It decrements by 1 every section. (i--)
 +
 
 +
==Creating the Loop==
 +
 
 +
Since we know what value i is when the code begins and at what value it ends, using our knowledge of loops we know that a [[For Loops|for loop]] would work best here. Lets do that now.
 +
<pre>
 +
for (int i=9; i>0; i--)
 +
        {
 +
            digit = isbn % 10;
 +
    isbn = isbn / 10;
 +
    total = total + digit * i;
 +
    System.out.println (digit + " * " + i + " for a running total of " + total);
 +
}
 +
</pre>
 +
 
 +
So what we have now is one section of code that will perform the same operation that the 9 previous sections of code did. In the first iteration of the loop, i will be equal to 9, then to 8, and so on until i = 1;
 +
 
 +
==Initializing Total==
 +
 
 +
If we tried to run the new code right now we would run into a problem. The problem is with the following code.
 +
<pre>
 +
int total;
 +
 
 +
total = total + digit * i;
 +
</pre>
 +
 
 +
The problem is that our variable 'total' is not initialized yet and in our for loop it adds itself. This means that in the first iteration of the for loop we would have.
 +
 
 +
<pre>
 +
total = (undefined) + digit * (9);
 +
</pre>
 +
 
 +
This will cause a compiling error, but it is easily remedied. Simply initialize total to be equal to 0 when you declare it.
 +
 
 +
=Printing Out 'X'=
 +
 
 +
Now that we have completed the first task of the case study, it is now time to make the program print out an 'X' whenever checkDigit is 10.
 +
 
 +
==Adding If-Else==
 +
 
 +
So when we're printing the final ISBN with the check digit on the end there are two things that could happen:
 +
1) If checkDigit is 10, print an 'X' rather than the digit.
 +
2) Else print out the checkDigit value.
 +
 
 +
The perfect structure to use here would be an [[The If-Else Statement|if-else]] statement. So lets do that now.
 +
 
 +
<pre>
 +
        checkDigit = total % 11;
 +
 
 +
        //if check digit is equal to 10 then print an 'X', otherwise print the checkDigit value
 +
if (checkDigit == 10)
 +
        {
 +
    System.out.println ("The check digit is: 'X'");
 +
    System.out.println ("\nThe 10-digit ISBN is: " + temp + 'X');
 +
}
 +
else
 +
        {
 +
    System.out.println ("The check digit is: " + total%11);
 +
    System.out.println ("\nThe 10-digit ISBN is: " + temp + checkDigit);
 +
</pre>
 +
 
 +
So, this structure states that if checkDigit is equal to 10, then the program will print out an 'X' and everyone other number will print out the checkDigit value.
  
 
=Sample Solution Code=
 
=Sample Solution Code=
Line 29: Line 167:
 
  */
 
  */
  
public class CaseStudy2_ISBN_Solution  {
+
public class CaseStudy2_ISBN_Solution   
 +
{
  
public static void main (String [] args) {
+
    public static void main (String [] args)  
 +
    {
  
                //variables declared here
+
        //variables declared here
String temp;        //temporary input string
+
        String temp;        //temporary input string
int isbn;          //9-digit ISBN
+
int isbn;          //9-digit ISBN
int digit;          //isolated ISBN digit
+
int digit;          //isolated ISBN digit
                int total = 0;      //total of isbn number when each digit is multiplied by check value
+
        int total = 0;      //total of isbn number when each digit is multiplied by check value
        int checkDigit;    //value of total%11(as per ISBN standard)
+
int checkDigit;    //value of total%11(as per ISBN standard)
  
                //get input
+
        //get input
temp= JOptionPane.showInputDialog ("Enter first 9 digits of ISBN");
+
temp= JOptionPane.showInputDialog ("Enter first 9 digits of ISBN");
isbn = Integer.parseInt (temp);
+
isbn = Integer.parseInt (temp);
  
                System.out.println ("You have entered " + temp + ".\n\nThe weighted value of the ISBN is:");
+
        System.out.println ("You have entered " + temp + ".\n\nThe weighted value of the ISBN is:");
  
for (int i=9; i>0; i--) {
+
for (int i=9; i>0; i--)  
digit = isbn % 10;
+
        {
isbn = isbn / 10;
+
            digit = isbn % 10;
total = total + digit * i;
+
    isbn = isbn / 10;
System.out.println (digit + " * " + 9 + " for a running total of " + total);
+
    total = total + digit * i;
}
+
    System.out.println (digit + " * " + i + " for a running total of " + total);
 +
}
 
 
                //calculate check digit
+
        //calculate check digit
                checkDigit = total % 11;
+
        checkDigit = total % 11;
 +
 
 +
        System.out.println ("The weighted total is: " + total);
  
        System.out.println ("The weighted total is: " + total);
+
        //if check digit is equal to 10 then print an 'X', otherwise print the checkDigit value
 +
if (checkDigit == 10)
 +
        {
 +
    System.out.println ("The check digit is: 'X'");
 +
    System.out.println ("\nThe 10-digit ISBN is: " + temp + 'X');
 +
}
 +
else
 +
        {
 +
    System.out.println ("The check digit is: " + total%11);
 +
    System.out.println ("\nThe 10-digit ISBN is: " + temp + checkDigit);
 +
}
  
                //if check digit is equal to 10 then print an 'X', otherwise print the checkDigit value
+
System.out.println ("\nProgrammed by COMP 1010 Instructors");
if (total%11 == 10) {
+
System.out.println ("Date: " + new Date());
System.out.println ("The check digit is: 'X'");
+
System.out.println ("*** End of Processing ***");
System.out.println ("\nThe 10-digit ISBN is: " + temp + 'X');
+
}
+
else {
+
System.out.println ("The check digit is: " + total%11);
+
System.out.println ("\nThe 10-digit ISBN is: " + temp + checkDigit);
+
}
+
  
System.out.println ("\nProgrammed by COMP 1010 Instructors");
+
    }//end main
System.out.println ("Date: " + new Date());
+
System.out.println ("*** End of Processing ***");
+
}//end main
+
 
}//end class
 
}//end class
 
</pre>
 
</pre>
Line 81: Line 225:
 
Case Study IV: [[Case_Study_IV|Day Four at Funky Books Inc.]]<br />
 
Case Study IV: [[Case_Study_IV|Day Four at Funky Books Inc.]]<br />
  
[[Category:Soultions]]
+
[[Category:Solutions]]

Latest revision as of 02:32, 6 December 2007

COMP 1010 Home > Java Fundamentals


Introduction

This is the solution page for Case Study II. Here you will find the sample solution code to the problem, as well as an explanation of how to arrive at this solution. The information required to complete this case study can be found in the chapters previous to this one.

The tasks were:

  • Use a loop to minimize repeated code.
  • Use an if statement to print out check digits of 10 as X.

   

{{{Body}}}



Sample Solution

This section will explain how to develop the solution to the tasks given in Case Study II.

Adding the Loop

Loops are a great way to code algorithms that follow a pattern. They allow you to take code that might have taken hundreds of lines and trim it down to a fraction of the size. You will see the effectiveness of a loop in this case study.

Find the Repetition

The first thing that needs to be done with this code is to look for the repetition. If we intend to add a loop, we will need to find what will be going into it. Let us take a look.

        //isolate last digit and multiply by 9
        digit = (isbn % 10);
        total = digit * 9;
        isbn = isbn / 10;
        System.out.println (digit + " * " + 9 + " for a running total of " + total);

        //isolate next digit and multiply by 8
        digit = (isbn % 10);
        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
        digit = (isbn % 10);
        total = total + digit * 7;
        isbn = isbn / 10;
        System.out.println (digit + " * " + 7 + " for a running total of " + total);

Just by looking at the first three sections of code we can already see a pattern. Its easy to see that each section does the same four actions: 1) Isolate the digit. 2) Add digit multiplied by its position to the total. 3) Remove the last digit from the ISBN. 4) Print out the running total.

Deciphering the Pattern

Now that we have found where the repetition is located in the code, we now have to figure out how to make an equation out of it. Lets look at the code for the 8th digit and compare each line to the sections for other digits.

digit = (isbn % 10);

Here we see that this line of code stays the same in every section. So lets look at the next line in a section.

total = total + digit * 8;

We see here that this equation is the same for each section, except for the multiplier. We can see that the number matches which ever digit it currently is. At the beginning it starts as a 9 for the ninth digit, then an 8 for the eighth digit, then all the way to 1 for the first one. The number is decrementing by 1 each section. This will be important to keep in mind when we decipher the pattern. For now lets look at the next line of code.

isbn = isbn / 10;

Again, this code is the same in every section. On to the section's last line of code.

System.out.println (digit + " * " + 8 + " for a running total of " + total);

Here we have another example where all the code stays the same except for the value of the multiplier, which happens to be the same value as the number that changed in the previous example. This number will decrement by 1 for each section of code.

Creating the Pattern

What we just learned from the previous section is that there is a number, we will call it the 'multiplier digit', that decrements by one every section of code. Lets treat that number as a variable, i. In the first section i = 9, the second section i = 8, the third i = 7, and so on until i = 1.

So what do know about the 'multiplier digit'?

   - We know it starts at 9. (i = 9) 
   - It decrements down until it reaches 1, then it stops. (i > 0)
   - It decrements by 1 every section. (i--)

Creating the Loop

Since we know what value i is when the code begins and at what value it ends, using our knowledge of loops we know that a for loop would work best here. Lets do that now.

for (int i=9; i>0; i--) 
        {
            digit = isbn % 10;
	    isbn = isbn / 10;
	    total = total + digit * i;
	    System.out.println (digit + " * " + i + " for a running total of " + total);
	}

So what we have now is one section of code that will perform the same operation that the 9 previous sections of code did. In the first iteration of the loop, i will be equal to 9, then to 8, and so on until i = 1;

Initializing Total

If we tried to run the new code right now we would run into a problem. The problem is with the following code.

int total;

total = total + digit * i;

The problem is that our variable 'total' is not initialized yet and in our for loop it adds itself. This means that in the first iteration of the for loop we would have.

total = (undefined) + digit * (9);

This will cause a compiling error, but it is easily remedied. Simply initialize total to be equal to 0 when you declare it.

Printing Out 'X'

Now that we have completed the first task of the case study, it is now time to make the program print out an 'X' whenever checkDigit is 10.

Adding If-Else

So when we're printing the final ISBN with the check digit on the end there are two things that could happen: 1) If checkDigit is 10, print an 'X' rather than the digit. 2) Else print out the checkDigit value.

The perfect structure to use here would be an if-else statement. So lets do that now.

        checkDigit = total % 11;

        //if check digit is equal to 10 then print an 'X', otherwise print the checkDigit value
	if (checkDigit == 10) 
        {
	    System.out.println ("The check digit is: 'X'");
	    System.out.println ("\nThe 10-digit ISBN is: " + temp + 'X');
	}
	else 
        {
	    System.out.println ("The check digit is: " + total%11);
	    System.out.println ("\nThe 10-digit ISBN is: " + temp + checkDigit);

So, this structure states that if checkDigit is equal to 10, then the program will print out an 'X' and everyone other number will print out the checkDigit value.

Sample Solution Code

import javax.swing.*;
import java.util.Date;

/**
 *
 * This program will read in the first 9 digits of an ISBN and print out the 9 digits
 * along with the valid 10th check digit. This code uses a loop structure to remove redundant code
 * Note that this code will handle the possibility of the check digit being an 'X'.
 *
 * @author:     1010 Instructors
 * @version:    2007-September
 *
 */

public class CaseStudy2_ISBN_Solution  
{

    public static void main (String [] args) 
    {

        //variables declared here
        String temp;        //temporary input string
	int isbn;           //9-digit ISBN
	int digit;          //isolated ISBN digit
        int total = 0;      //total of isbn number when each digit is multiplied by check value
	int checkDigit;     //value of total%11(as per ISBN standard)

        //get input
	temp= JOptionPane.showInputDialog ("Enter first 9 digits of ISBN");
	isbn = Integer.parseInt (temp);

        System.out.println ("You have entered " + temp + ".\n\nThe weighted value of the ISBN is:");

	for (int i=9; i>0; i--) 
        {
            digit = isbn % 10;
	    isbn = isbn / 10;
	    total = total + digit * i;
	    System.out.println (digit + " * " + i + " for a running total of " + total);
	}
	
        //calculate check digit
        checkDigit = total % 11;

        System.out.println ("The weighted total is: " + total);

        //if check digit is equal to 10 then print an 'X', otherwise print the checkDigit value
	if (checkDigit == 10) 
        {
	    System.out.println ("The check digit is: 'X'");
	    System.out.println ("\nThe 10-digit ISBN is: " + temp + 'X');
	}
	else 
        {
	    System.out.println ("The check digit is: " + total%11);
	    System.out.println ("\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

Links To Case Studies

Case Study I: Day One at Funky Books Inc.
Case Study II: Day Two at Funky Books Inc.
Case Study III: Day Three at Funky Books Inc.

Case Study IV: Day Four at Funky Books Inc.