Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Solution to Methods Parameter 1. Tracing Programs For each program below, show what is displayed on the screen when the code executes. import java.util.Arrays; public class ReferenceSemantics1 { public static int mystery(int a, int [] b) { a++; b[0] = 0; b = new int[4]; return a / 2; } public static void main(String [] args) { int x = 10; int [] y = {3, -3, 3}; x = x + mystery(x, y); System.out.println(x); System.out.println(Arrays.toString(y)); } } screen 15 [0, -3, 3] import java.io.File; public class ReferenceSemantics3 { public static void mystery(boolean a, File f) { a = !a; f.delete(); // this deletes the file (whose name is stored in f) // from the hard drive, if it exists. f = new File("output"); return; } public static void main(String [] args) { boolean x = false; File y = new File("input"); mystery(x, y); System.out.println(x); System.out.println(y.getName()); } } screen false input public class NestedCalls1 { public static void mystery1(int a) { System.out.println("m 1"); if(a > 0) { mystery2(-a); System.out.println("here?"); } System.out.println("and here?"); } public static void mystery2(int b) { System.out.println("m 2"); if(b > 0) { System.out.println("here 2?"); mystery1(b – 10); } System.out.println("and here 2?"); } public static void main(String [] args) { System.out.println("main"); int x = 3; mystery1(x); mystery2(x); System.out.println("what about here?"); } } screen main m 1 m 2 and here 2? here? and here? m 2 here 2? m 1 and here? and here 2? what about here? public class NestedCalls2 { public static int mystery1(int a) { System.out.println("m 1"); return a / 2; } public static String mystery2(int b) { String s = "m 2"; System.out.println(s); for(int i=0; i<b ; i++) { s = s + " " + i; } return s; } public static void main(String [] args) { System.out.println("main"); System.out.println(mystery2(mystery1(4))); System.out.println("end main"); } } screen main m 1 m 2 m 2 0 1 end main 2. Writing Short Methods a. Write a method that takes an integer A as an argument. The method should display the value of A squared on the screen. // for these kinds of questions, you only need to write the method definition // you do NOT need to write the import statements, or "public class <name>" public static void displaySquare(int A) { System.out.println("the square of " + A + " is " + (A * A)); } b. Write a method that takes an integer N as an argument. The method should display a line with N copies of the '*' character on the screen. public static void displayLineOfStars(int N) { for(int i=0; i<N; i++) { System.out.print("*"); } System.out.println(); } c. Write a method that takes an array of chars A, an integer j, and an integer k as arguments. The method should return a String consisting of the characters in A between positions j and k. public static String subCharArray(char [] A, int j, int k) { String ret = ""; for(int i=j; i<k; i++) { ret = ret + char[i]; } return ret; } 3. Methods and arrays a. Let’s say I have an array of integers entered by the user. Write a method that displays the biggest integer in the array. public static void displayBiggestInt(int [] arr) { int biggest = arr[0]; for(int i=1; i<arr.length; i++) { if(arr[i] > biggest) { biggest = arr[i]; } } System.out.println(“biggest is “ + biggest); } b. Write a main() method that creates an array of integers, and uses the method from the above to find and display the biggest integer. public static void main(String [] args) { int [] myArr = {12, 22, -17, 105, -1000, 200, -10, 26}; displayBiggestInt(myArr); } c. Modify your method so that it returns the biggest integer in the array, instead of displaying it. public static int findBiggestInt(int [] arr) { int biggest = arr[0]; for(int i=1; i<arr.length; i++) { if(arr[i] > biggest) { biggest = arr[i]; } } return biggest; } d. Change the main() method so that it uses the new version of your biggest-integer-finder, and displays the biggest integer. public static void main(String [] args) { int [] myArr = {12, 22, -17, 105, -1000, 200, -10, 26}; int bigVal = findBiggestInt(myArr); System.out.println(“biggest is “ + bigVal); } e. Write a method that swaps the values stored in positions pos1 and pos2 in an array. For instance, if I created an array in main memory that looked like this: int [] x = {7, -5, 12, 22, 16}; Then, if I execute // In this example, pos1 is 2, pos2 is 4 swap(x, 2, 4); Then x should contain the values {7, -5, 16, 22, 12} after the swap method executes, because it has swapped the values at positions 2 and 4. Note this is only an example, and your method should work for any integer array and any 2 positions between 0 and the end of the array. Start by coming up with the method signature: public static void swap(int [] arr, int pos1, int pos2) { } f. Next, come up with an algorithm for the swap method. It helps to create a temporary variable that stores one of the two elements being swapped. Swap algorithm Input: array arr, position pos1, position pos2 Let temp = arr[pos1] Let arr[pos1] = arr[pos2] Let arr[pos2] = temp g. Now fill in the body of your method by turning your algorithm into code. If your method has a non-void return type, remember to include a return statement with a value of the appropriate type. public static void swap(int [] arr, int pos1, int pos2) { int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; } h. Think about how you would write a main() method that creates an array, finds the biggest value of the array, and swaps it with the value at position 0. Before you do this, answer this: why can you NOT use the method for finding the biggest integer from above? The swap method needs to know the position of the biggest value in the array, but the findBiggestInt method returns the value of the biggest value in the array. i. Modify the method for finding the biggest integer (above) so that it returns the position rather than value of the biggest integer in the array. public static int findBiggestIntPos(int [] arr) { int biggestPos = 0; for(int i=1; i<arr.length; i++) { if(arr[i] > arr[biggestPos]) { biggestPos = i; } } return biggestPos; } j. Now write the main() method that creates an array, finds the position of the biggest value of the array (using your modified method), and swaps the biggest value with the value stored at position 0. public static void main(String [] args) { int [] myArr = {12, 22, -17, 105, -1000, 200, -10, 26}; int bigPos = findBiggestIntPos(myArr); swap(myArr, bigPos, 0); System.out.println(Arrays.toString(myArr)); } k. As the result a insertionSort() method can be completed to sort an array. Here is the algorithm for insertionSort: InsertionSort Input: an array of integers D output: D is sorted, largest element at position 0, then next-largest, and so on. Let numSortedElements = 0; while numSortedElements < length of D: Let posNextLargest = findBiggestPos(D, numSortedElements, length of D) swap(D, numSortedElements, posNextLargest) Let numSortedElements = numSortedElements + 1 Note that this algorithm is only partially defined, since we made use of 2 sub-routines. We already defined the “swap” routine above. We defined a version of the findBiggestPos routine above as well, but this one’s a bit different. Here’s the algorithm: Find Biggest Position in Portion of an Array Input: an array of integers D startPos, the first position to start looking endPos, the last position to look at Output: the position of the biggest element in D between the positions startPos and endPos Let posBiggest = startPos Let curPos = startPos + 1 while curPos<=endPos: if D[curPos] > D[posBiggest]: posBiggest = curPos Let curPos = curPos + 1 return posBiggest import java.util.Arrays; public class InsertionSorter { public static int findBiggestIntPos( int [] arr, int startPos, int endPos) { int biggestPos = startPos; for(int i=startPos+1; i<=endPos; i++) { if(arr[i] > arr[biggestPos]) { biggestPos = i; } } return biggestPos; } // copy from above public static void swap(int [] arr, int pos1, int pos2) { int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; } public static void insertionSort(int [] arr) { int numSorted = 0; while(numSorted < arr.length) { int posBiggest = findBiggestIntPos( arr, numSorted, arr.length-1); swap(arr, numSorted, posBiggest); numSorted++; } } // to test our insertion sort public static void main(String [] args) { int [] test = {-5, 12, -20, 10, -15, 100, -22}; insertionSort(test); System.out.println(Arrays.toString(test)); } } 4. More programming with methods a. Write a method called isEven that returns whether an integer is even or not. public static boolean isEven(int N) { return (N % 2 == 0); } b. Write a method called isPerfect that returns whether an integer is a perfect number or not. A perfect number is one that is equal to the sum of its factors (not including the number itself as a factor). For instance, 6 is a perfect number because its factors are 1, 2, and 3, and 1+2+3=6. 28 is the next perfect number, because 1+2+4+7+14=28. public static boolean isPerfect(int N) { int factorSum = 0; for( int possibleFactor = 1; possibleFactor<N; possibleFactor++ ) { if(N % possibleFactor == 0) { // actual factor! factorSum += possibleFactor; } } return (factorSum == N); } c. Write a loop that finds the next perfect number after 28. Use the isPerfect method from above (you don’t have to solve (b) to do this one, just pretend that you have a correct version of isPerfect() defined). public static int perfectNumAfter28() { for(int maybePerfect = 29; true; maybePerfect++) { if( isPerfect(maybePerfect)) { // found one! return maybePerfect; } } } d. Write a method that returns the average value of a 2D array of doubles. public static double averageOf2DArray(double [][] array) { double sum = 0.0; int numElements = 0; for(int row=0; row<array.length; row++) { for(int col=0; col<array[row].length; col++) { sum += array[row][col]; numElements++; } } return sum / numElements; }