Write a method that returns an array list of Character from a string using the following header: public static ArrayList toCharacterArray(String s) For example toCharacterArray("abc") returns an array list that contains characters ‘a’, ‘b’ and ‘c’. Write a test method that prompts the user to enter a String. Call the method toCharacterArray() on the input string. Print the elements of the Character array list separated by exactly one space. Here is a sample run: Enter the input string: Stony Brook Elements of the Character array list: S t o n y B r o o k.

Answered on

To complete this task, we will need to create a method named `toCharacterArray` that takes a `String` as the input and returns an `ArrayList`. We will also create a test method that prompts the user for a string, calls the `toCharacterArray` method with that string, and then prints out the elements of the created array list separated by spaces. Below is the code for this:

```java import java.util.ArrayList; import java.util.Scanner;

public class StringToCharacterArrayList {

// The toCharacterArray method public static ArrayList toCharacterArray(String s) { ArrayList characterList = new ArrayList(); for(int i = 0; i < s.length(); i++) { characterList.add(s.charAt(i)); } return characterList; }

// The test method public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the input string: "); String userInput = input.nextLine(); // Call the toCharacterArray method ArrayList characters = toCharacterArray(userInput); // Print the elements of the array list System.out.print("Elements of the Character array list: "); for(Character c : characters) { System.out.print(c + " "); } input.close(); } } ```

When you run this program, it should behave as described in your example. For instance, if you input "Stony Brook", the output will be: ``` Enter the input string: Stony Brook Elements of the Character array list: S t o n y B r o o k ```

Related Questions