In Java 1 Prompt the user to enter a string of their choosin

In Java.

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

Ex:

(2) 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. (2 pts)

(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(). (2 pts)

Ex:

import java.util.Scanner;

public class TextAnalyzer {
   // Method counts the number of characters
   public static int getNumOfCharacters(final String usrStr) {
      /* Type your code here. */
    
      return 0;
   }

   public static void main(String[] args) {
      /* Type your code here. */
    
      return;
   }
}

Solution

import java.util.Scanner;
public class HelloWorld{

// Method counts the number of characters
public static int getNumOfCharacters(final String usrStr) {
/* Type your code here. */
int count=0;
//counting characters
for(int i=0;i<usrStr.length();i++)
count++;
return count;
}

// Method prints the string without whitespaces
public static void outputWithoutWhitespace(final String usrStr){
String strwithoutSpaces;
//removing spaces
strwithoutSpaces = usrStr.replaceAll(\"\\\\s+\",\"\");
System.out.println(\"String with no whitespace: \"+strwithoutSpaces);


}
public static void main(String []args){
Scanner sc=new Scanner(System.in);
//variable to store str
String str;
//asking user to enter the string
System.out.print(\"Enter a sentence or phrase: \");
str=sc.nextLine();
  
System.out.println(\"You entered: \"+str);
//calling getNumOfCharacters to count the number of characters
System.out.println(\"Number of characters: \"+getNumOfCharacters(str));
//calling function outputwithoutspaces
outputWithoutWhitespace(str);
}
}
//end of code

*********OUTPUT******
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: TheonlythingwehavetofearIsfearitself.
*********OUTPUT******

Note:Please ask in case of any doubt,Thanks.

In Java. (1) Prompt the user to enter a string of their choosing. Output the string. (1 pt) Ex: (2) Complete the getNumOfCharacters() method, which returns the
In Java. (1) Prompt the user to enter a string of their choosing. Output the string. (1 pt) Ex: (2) Complete the getNumOfCharacters() method, which returns the

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site