Complete the getNumOfCharacters() method, which returns the number of characters in the user's string. We encourage you to use a for loop in this function. (3) In main(), call the getNumOfCharacters() method and then output the returned result. (1 pt) (4) Implement the outputWithoutWhitespace() method, which outputs the string's characters except for whitespace (spaces, tabs). Note: A tab is '\t'. Call the outputWithoutWhitespace() method in main().

Respuesta :

Answer:

The Java code is given below with appropriate comments

Explanation:

//Program

//Import the necessary libraries

import java.util.Scanner;

//Define the class

public class CountStringCharacters

{

//Start the main method

public static void main(String[] args)

{

//Prompt the user to enter the input line

Scanner scan = new Scanner(System.in);

System.out.println("Enter a sentence or phrase: ");

String s = scan.nextLine();

 

//Take the number of characters and keep the count

int numOfCharacters = getNumOfCharacters(s);

System.out.println("You entered: "+s);

System.out.println("Number of characters: "+numOfCharacters);

 

//Call the method outputWithoutWhitespace

outputWithoutWhitespace(s);

}

//The method getNumOfCharacters

public static int getNumOfCharacters(String s)

{

int numOfCharCount = 0;

for(int i=0; i<s.length();i++)

{

numOfCharCount++;

}

return numOfCharCount;

}

//Definition of the method outputWithoutspace

public static void outputWithoutWhitespace(String s)

{

String str = "";

for(int i=0; i<s.length();i++)

{

char ch = s.charAt(i);

if(ch != ' ' && ch != '\t')

str = str + ch;

}

System.out.println("String with no whitespace: "+str);

}

}