I need someone to show me how to do this 3 step JAVA script programming challeng
ID: 3870656 • Letter: I
Question
I need someone to show me how to do this 3 step JAVA script programming challenge.
public class WordSeparator
{
private String formatted;
/*step1: Write a method named convert. It accepts a sentence. The method then convert the
sentence to a string in which the words are seperated by spaces and only the first word
starts with an uppercase letter. The method returns the modified sentence.
*/
public String getFormatted()
{
return formatted;
}
}
import java.util.Scanner;
public class WordSepDemo
{
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence with no spaces between the words");
System.out.println("and the first letter of each word capitalized.");
System.out.println("Example: StopAndSmellTheRoses");
System.out.print("> ");
input = keyboard.nextLine();
System.out.println(input);
//step2: Create a WordSeparator object with the input.
//step3: Display the formatted text using getFormated() method.
}
}
Explanation / Answer
WordSepDemo.java
import java.util.Scanner;
public class WordSepDemo
{
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence with no spaces between the words");
System.out.println("and the first letter of each word capitalized.");
System.out.println("Example: StopAndSmellTheRoses");
System.out.print("> ");
input = keyboard.nextLine();
System.out.println(input);
//step2: Create a WordSeparator object with the input.
WordSeparator w = new WordSeparator();
w.convert(input);
//step3: Display the formatted text using getFormated() method.
System.out.println(w.getFormatted());
}
}
WordSeparator.java
public class WordSeparator
{
private String formatted;
/*step1: Write a method named convert. It accepts a sentence. The method then convert the
sentence to a string in which the words are seperated by spaces and only the first word
starts with an uppercase letter. The method returns the modified sentence.
*/
public void convert(String sentence) {
formatted = sentence.charAt(0)+"";
formatted = formatted.toUpperCase();
for(int i=1; i<sentence.length(); i++){
if(Character.isUpperCase(sentence.charAt(i))) {
formatted = formatted+" "+(sentence.charAt(i)+"").toLowerCase();
} else {
formatted = formatted+(sentence.charAt(i)+"").toLowerCase();
}
}
}
public String getFormatted()
{
return formatted;
}
}
Output:
Enter a sentence with no spaces between the words
and the first letter of each word capitalized.
Example: StopAndSmellTheRoses
> StopAndSmellTheRoses
StopAndSmellTheRoses
Stop and smell the roses