172k views
4 votes
(1) Prompt the user to enter a string of their choosing. Output the string.

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 GetNumOfCharacters() function, which returns the number of characters in the user's string. Use a for loop in this function for practice. (2 pts)
(3) In main(), call the GetNumOfCharacters() function and then output the returned result. (1 pt) (4) 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(). (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 characters: 46 String with no whitespace: The only thing we have to fear is fear itself.

1 Answer

3 votes

Answer:

The solution is given in the explanation section

See comments for detailed explanation of each step

Step-by-step explanation:

import java.util.Scanner;

class Main {

public static void main(String[] args) {

//Prompting the User to enter a String

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

//Receiving the string entered with the Scanner Object

Scanner in = new Scanner (System.in);

String user_word = in.nextLine();

//OutPuting User entered string

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

//Calling the GetNumOfCharacters Method

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

//Calling the OutputWithoutWhitespace Mehtod

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

}

//Creating the function GetNumOfCharacters()

//This function will return the number of characters

// in the string entered by the user_word

public static int GetNumOfCharacters (String word) {

int noOfCharacters = 0;

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

noOfCharacters++;

}

return noOfCharacters;

}

//Creating the OutputWithoutWhitespace() method

//This method will remove all tabs and spaces from the original string

public static String OutputWithoutWhitespace(String word){

//Use the replaceAll all method of strings to replace all whitespaces with no space.

String new_string = word.replaceAll(" ","");

return new_string;

}

}

User Ronnyfm
by
5.8k points