Consider the following method, which takes a String object as its only parameter
ID: 3631023 • Letter: C
Question
Consider the following method, which takes a String object as its only parameter:public static void processString(String str) {
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
}
Describe briefly (in clear, non-technical terms) what this method does. For example, you could try the following method calls:
processString("Boston");
processString("Terriers");
(3 points) Write a method called printReverse that takes a String object as its only parameter and prints the string in reverse order on a single line. For example, printReverse("Boston") should print the following:
notsoB
and printReverse("Terriers") should print
sreirreT
Hint: Use the processString method as a starting point, and determine what changes are needed to obtain the behavior specified for printReverse.
(4 points) Fill in the blanks below to create a method called middleChar that takes a String object as its only parameter and returns the character in the "middle" of the string. This method should not do any printing. Rather, it should extract the appropriate character and return it. The character should be returned as a value of type char, not as a value of type String.
For example:
middleChar("clock") should return the character 'o' (not the string "o")
middleChar("Boston") should return the character 's' (not the string "s"). Note that when the string has an even number of characters, the method returns the first of the two middle characters (the one closer to the beginning of the string).
Here is the template that you should fill in:
public static ______ middleChar(____________) {
int middleIndex = _____________; // see the hint below
// Add one or two additional lines that extract
// and return the middle character.
}
Hint: The variable middleIndex should be assigned the result of a computation that determines the index of the character that you need to extract. The same computation should work regardless of whether the string has an odd or even number of characters, so you can base your computation on whichever case (odd or even) seems easier. You may assume that the string has at least one character.
Explanation / Answer
1)this method takes in a String. Each character of the string is printed out in a row, with the first character of the string at the top. a)processString("Boston"); output: B o s t o n b)processString("Terriers"); T e r r i e r s 2) public static void printReverse(String str) { for (int i = str.length()-1; i >= 0; i--) { System.out.println(str.charAt(i)); } } 3) public static char middleChar(String str) { int middleIndex = (str.length() - 1)/2; return (str.charAt(middleIndex)); }