66.6k views
3 votes
Complete the GetNumOfCharacters() function, which returns the number of characters in the user's string. We encourage you to use a for loop in this function.

In main(), call the GetNumOfCharacters() function and then output the returned result.Implement the OutputWithoutWhitespace() function. OutputWithoutWhitespace() outputs the string's characters except for whitespace (spaces, tabs). Note: A tab is '\t'. Call the OutputWithoutWhitespace() function in main().

User JensT
by
5.5k points

1 Answer

4 votes

Solution and Explanation:

//Code to copy

//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);

}

}

User KursoR
by
5.6k points