143k views
3 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.

User Erosb
by
5.1k points

1 Answer

2 votes

Answer:

See solution below

See comments for explanations

Step-by-step explanation:

import java.util.*;

class Main {

public static void main(String[] args) {

//PrompT the User to enter a String

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

//Receiving the string entered with the Scanner Object

Scanner input = new Scanner (System.in);

String string_input = input.nextLine();

//Print out string entered by user

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

//Call the first method (GetNumOfCharacters)

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

//Call the second method (OutputWithoutWhitespace)

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

}

//Create the method GetNumOfCharacters

public static int GetNumOfCharacters (String word) {

//Variable to hold number of characters

int noOfCharactersCount = 0;

//Use a for loop to iterate the entire string

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

//Increase th number of characters each time

noOfCharactersCount++;

}

return noOfCharactersCount;

}

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

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

return stringWithoutWhiteSpace;

}

}

User Jeroen Dirks
by
4.8k points