Please help in Java Write a method called joinWords that tak
Please help in Java:
Write a method called joinWords that takes an array of String objects and returns a single String that results from concatenating all the strings together, separated by spaces. Do not add a space after the last element, nor before the first one. For example, calling joinWords with array {“Thank”, “goodness”, “it”, “is”, “Friday!”}, will return “Thank goodness it is Friday!” (without the quotes).
a. You should specify the size of the array in main.
b. Initialize the string array in main, without user input
c. Print the output of the new string
This is what I have so far and its only printing out Friday!:
public static void main(String[] args) {
String words[]={\"Thank\",\"goodness\",\"it\",\"is\",\"Friday!\"};
String newword=\"\";
String word=joinWords(words);
System.out.println(word);
}
public static String joinWords(String[] words){
String newword = \"\";
for(int i=0;i<words.length;i++){
newword=words[i];
if(i<words.length-1){
}
}
return newword;
}
}
Solution
StringConcatination.java
public class StringConcatination {
public static void main(String[] args) {
//Declaring string variable
String newString=\"\";
//Declaring and initializing String type array
String words[]={\"Thank\",\"goodness\",\"it\",\"is\",\"Friday!\"};
newString=joinWords(words);
//after removing the leading and trailing spaces displaying the sentence
System.out.println(newString.trim());
}
private static String joinWords(String[] words) {
String newString=\"\";
//This for loop will concatenate the words into sentence
for(int i=0;i<words.length;i++)
{
newString+=\" \"+words[i];
}
return newString;
}
}
________________________
Output:
Thank goodness it is Friday!
________________________
Using Java 8:
public class HelloWorld{
public static void main(String []args){
//Declaring string variable
String newString=\"\";
//Declaring and initializing String type array
String words[]={\"Thank\",\"goodness\",\"it\",\"is\",\"Friday!\"};
newString=joinWords(words);
//after removing the leading and trailing spaces displaying the sentence
System.out.println(newString);
}
private static String joinWords(String[] words) {
String newString=\"\";
newString=String.join(\" \",words);
return newString;
}
}
_________________
Output:
Thank goodness it is Friday!
_______Thank You

