1 Prompt the user to enter a string of their choosing Output

(1) Prompt the user to enter a string of their choosing. Output the string. (1 pt)

Ex: Enter a sentence or phrase: The only thing we have to fear is fear itself. You entered: The only thing we have to fear is fear itself.

(2) Complete the GetNumOfSpaces() function, which returns the number of spaces in the user\'s string. (2 pts)

(3) In main(), call the GetNumOfSpaces() function and then output the returned result. (1 pt)

(4) Implement the OutputWithoutWhitespace() function. OutputWithoutWhitespace() outputs the string\'s characters except for white spaces (spaces, tabs).

Note: A tab is \'\\t\'. Call the OutputWithoutWhitespace() function in main(). (2 pts)

Ex: Enter a sentence or phrase: The only thing we have to fear is fear itself.

You entered: The only thing we have to fear is fear itself.

Number of spaces: 9

String with no whitespace: Theonlythingwehavetofearisfearitself.

Solution

package com.bp.common;

import java.util.Scanner;

public class StringFinder {
   public static void main(String[] args) {
       // initializing
       Scanner scanner = new Scanner(System.in);
       System.out.println(\"enter the string\");
       // reading the string
       String sentence = scanner.nextLine();
       // calling the function
       int no = StringFinder.getNoOfSpaces(sentence);
       System.out.println(\"the no of spaces:\" + no);
       // calling the function
       String message = StringFinder.callTheOutputWithoutWhiteSpaces(sentence);
       System.out.println(\"the string without whitespaces:\"+message);

   }

   public static String callTheOutputWithoutWhiteSpaces(String sentence) {
       String StringOutputWithoutSpaces = sentence.replaceAll(\"\\\\s+\", \"\");
       return StringOutputWithoutSpaces;

   }

   public static int getNoOfSpaces(String sentence) {

       int countSpace = 0;
       for (char d : sentence.toCharArray()) {
           if (d == \' \') {
               countSpace++;
           }

       }

       return countSpace;
   }
}

output

enter the string

The only thing we have to fear is fear itself.

Number of spaces: 9

String with no whitespace: Theonlythingwehavetofearisfearitself.

(1) Prompt the user to enter a string of their choosing. Output the string. (1 pt) Ex: Enter a sentence or phrase: The only thing we have to fear is fear itself
(1) Prompt the user to enter a string of their choosing. Output the string. (1 pt) Ex: Enter a sentence or phrase: The only thing we have to fear is fear itself

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site