54.5k views
2 votes
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.

User Alba
by
5.0k points

1 Answer

3 votes

Answer:

Following are the program in Java Programming language

import java.util.*; //import package.

public class Main //define class main

{

public static ArrayList<Character>toCharacterArray(String s) //define function

{

ArrayList<Character> ob = new ArrayList<Character>(); //create ArrayList object.

for(char ch1: s.toCharArray())// iterating over the loop

{

ob.add(ch1); //add Character in list.

}

return ob; //return the object i.e return the value

}

public static void main(String args[]) // main method.

{

String str; // variable declaration.

int i; //define variable.

Scanner ob1 = new Scanner(System.in); //creating scanner class object.

System.out.print("Enter any string: "); //message

str = ob1.nextLine();//input value in str variable.

ArrayList<Character> ob2 = toCharacterArray(str); //create ArrayList reference variable and call toCharacterArray() function

System.out.print("Elements of the character array list: ");//message

for(i = 0;i<ob2.size();i++) //loop

{

System.out.print(ob2.get(i) + " "); //print value.

}

}

}

Output:

Enter any string: Stony Brook

Elements of the character array list: S t o n y B r o o k

Step-by-step explanation:

  • In the above java program firstly we import the package. Then we define a class that is "Main". In this class we define a function that is "toCharacterArray()" function and pass a string variable that is "s". After that, we create an ArrayList class object that is "ob" and define a loop. The loop is used to take input value and return its value.
  • Then we define a main function. In the main function, we define a variable that is "i" and "str".
  • Finally create an ArrayList object and use the loop for print inserted value with a separate of one space.
User Mukesh Lokare
by
5.6k points