Difference between revisions of "Add Area Code"

From CompSciWiki
Jump to: navigation, search
Line 15: Line 15:
 
|SideSection=
 
|SideSection=
 
It may take a while to get used to breaking one method into multiple methods.  When I first started coding I would have tons of repeated code that I would copy and paste all over.  Now that I know how to use methods it would be hard to go back to not using them.
 
It may take a while to get used to breaking one method into multiple methods.  When I first started coding I would have tons of repeated code that I would copy and paste all over.  Now that I know how to use methods it would be hard to go back to not using them.
 
<BR>
 
  
  

Revision as of 12:41, 6 April 2010

Back to the Program-A-Day homepage

Problem

Write a method which will take a three digit area code and a phone number and combine these into one value. Print this value in main.

Example:
combineNumber(204, 4881234);

Output:
2044881234

 

By Students...

It may take a while to get used to breaking one method into multiple methods. When I first started coding I would have tons of repeated code that I would copy and paste all over. Now that I know how to use methods it would be hard to go back to not using them.

Solution

The solution... To solve this problem we are going to create a skeleton structure. We know that we will have two methods: main & combineNumber. We know that combineNumber will accept two integers and return an integer:

public static void main()
{
}
public static int returnArray( int areaCode, int phoneNumber  )
{
}


Now that we have the skeleton we can start filling in main. We know that main will pass an area code and a number to combineNumber. combineNumber will return a integer which we will store in a temporary place holder and print:

public static void main()
{
   int temp;

   temp = combineNumber(204, 4881234); // instead of storing in temp you could also just print this directly

   System.out.println(temp);
}


Now we will fill in combineNumber. We know that it will be passed two numbers and we will need to combine them into one number. We can't just add them together though. We will need to change the area code to be area code + 0000000. This will cause it to be added onto the start of the phone number:

public static int combineNumber( int areaCode, int phoneNumber )
{
   areaCode = areaCode * 10000000;      
   
   return (areaCode + phoneNumber);
}

Code

Solution Code

Back to the Program-A-Day homepage