Question: Solve in JAVA In this problem, you will write a method called getMiddleChars that finds and returns the middle characters of the given text. If
Solve in JAVA
In this problem, you will write a method called getMiddleChars that finds and returns the "middle characters" of the given text. If there are an odd number of characters, return the middle 3. If there are an even number of characters, return the middle 2. If there are not enough characters in the original String to do this, return all the characters that there are.
For example, getMiddleChars("bamboozle") returns "boo", and getMiddleChars("lagoon") returns "go".
You must use appropriate methods of the String, Character, and/or StringBuilder classes to write your solution. Suggested methods for this problem:
String.length
String.substring
Tips:
How can you compute the middle index from the length of the original String?
From there, how do you get the start index of the substring based on the middle index?
Then, use the number of characters you want to extract to determine the end index for the substring.
Be sure to pass all the test cases and use good style. A Javadoc comment has been provided for you, but you need to write the method header and implementation.
import java.util.Scanner;
class WhatsInTheMiddle { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a line of text:"); String inputLine = scanner.nextLine(); System.out.printf("Middle letters: %s ", getMiddleChars(inputLine)); } /** * Gets the middle characters of a String, 3 if there are an odd number * or 2 if there are an even number. * * @param text The String from which to get the middle. * @return The middle 2-3 characters of the source String, or the whole * source String if there are fewer than 3 characters. */ // TODO: Implement the 'getMiddleChars' method here. }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
