L18Answers - 73. Write the charsMatchExactly() method so...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 73. Write the charsMatchExactly() method so that it correctly calculates the number of characters which are exactly the same, and in exactly the same position in the two Strings which can be of any length. You can assume that the two Strings which are passed to the method as parameters are the same length. If you complete the method correctly, the output of the following code: String s1 = "abcdefgh"; String s2 = "cbadzzgz"; int matches = charsMatchExactly(s1, s2); System.out.println("Matches: " + matches); would be: Matches: 3 private int charsMatchExactly(String a, String b) { int count = 0; for (int i = 0; i < a.length(); i++) { if (a.charAt(i) == b.charAt(i) ) { count++; } } return count; } 74. Complete the randomOddDigit() method below which should return a random odd digit (either 1, 3, 5, 7, or 9). The randomOddDigit() method must return either 1, 3, 5, 7 or 9 each time it is called. Each digit should have the same probability of being returned. private int randomOddDigit() { String possibleDigits = "13579"; int pos = (int) (Math.random() * possibleDigits.length()); char c = possibleDigits.charAt(pos); int digit = Integer.parseInt("" + c); return digit; } 75. Complete the method, doubleArray(), which is passed an int array as a parameter. The method returns a new array with each element equal to double the corresponding element of the parameter array. For example, executing the following code with the completed method: public void start() { int a = {1, 2, 3}; int b = doubleArray(a); System.out.println(b[0] + " " + b[1] + " " + b[2]); } private int doubleArray(int nums) { int a = new int[nums.length]; for (int i = 0; i < a.length(); i++) { a[i] = nums[i] * 2; } return a; } gives the output:...
View Full Document

This note was uploaded on 03/01/2012 for the course COMPSCI 101 taught by Professor Adrianaferraro during the Summer '12 term at Auckland.

Page1 / 2

L18Answers - 73. Write the charsMatchExactly() method so...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online