Download KeyForWritingMethodsWksht2

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Key For Writing Methods – Practice Worksheet 2
Name
1. Write the method countFactors(). This method takes an integer parameter numb and then counts up and returns the
number of integers that divide into it (evenly). For example, countFactors( 12 ) returns 6 since there are 6 factors (1, 2, 3,
4, 6, 12). Another example: countFactors( 7 ) should return 2.
public int
countFactors( int numb )
{
int count =
0
;
for( int possFactor = 1; possFactor <= numb; possFactor++ )
{
if( numb%possFactor = = 0 )
count++;
}
return count ;
}
2. Write the method findHypotenuse(). This method takes two double parameter a and b; it uses these parameters to find
the length of the hypotenuse of a right triangle where a and b are the lengths of the legs of the right triangle. For example,
findHypotenuse( 3.0, 4.0 ) returns 5.0.
public double findHypotenuse( double a, double b )
{
double cSqrd = a*a + b*b;
double c = Math.sqrt( cSqrd );
return c;
//or, in one line:
return Math.sqrt( a*a + b*b );
}
3. Write the method getMedian(). This method takes an ArrayList of Integers as it's parameter and returns the median.
Assume that the data is in ascending order and that there is at least one element in the list. (NB: data must be sorted to find
the median.) The median of a sorted list of numbers is:
a) the middle number in the list (the number in the middle position) if the list has an odd number of elements OR
b) the average of the two "middle" numbers in the list if the list has an even number of elements
For the list [3, 7, 9, 12, 14], the median is 9 since there are an odd number of elements and 9 is in the middle position.
For the list [3, 7, 9, 12], the median is 8 (the average of 7 and 9) since there are an even # of elements and 7 and 9 are "in
the middle".
public int getMedian( ArrayList<Integer> list ) {
int median;
if( list.size() % 2 = = 1 ) {
int middlePos = list.size() / 2;
median = list.get( middlePos );
//doing the odd case first
//test it out…recall that 5/2 is 2 in Java
//doing the even case…we don't need an if here
} else {
int highMidPos = list.size() / 2;
int lowMidPos = highMidPos – 1;
//size of 4 gives 3 here…which is the "second" middle
//now, average the two values in those positions
median = ( list.get( highMidPos ) + list.get( lowMidPos ) ) / 2;
}
return median;
}
Related documents