JAVA PLZ (1) Prompt the user to enter a string of their choosing. Output the str
ID: 3700349 • Letter: J
Question
JAVA PLZ
(1) Prompt the user to enter a string of their choosing. Output the string. (1 pt)
Sample input:
Sample output for above input:
(2) Complete the getNumOfCharacters(userStr) method, which returns the number of characters in the user's string. (2pts)
We encourage you to use a for loop in this function. Use the following method header:
public static int getNumOfCharacters(final String usrStr)
(3) In main(), call the getNumOfCharacters(userStr) method and then output the returned result. (1 pt)
Sample input:
Sample output for above input:
(4) Implement the method outputWithoutWhitespace(userStr) which outputs the string's characters except for whitespace (spaces, tabs). Note: A tab is ' '. Call the outputWithoutWhitespace(userStr) method in main(). (2 pts)
Sample input:
Sample output for above input:
TextAnalyzer.java Load default template... 1 import java.util.Scanner; 3 public class TextAnalyzer 4// Method counts the number of characters and returns the count 5 public static int getNumofCharacters(final String usrStr) / Type your code here./ return e; I/ return the number of characters here 8 10 public static void outputwithoutwhiteSpace (String userStr) This is a void function so you should output the new string inside this method You can use a for loop to iterate through each character in the string and if the character is not a t' or a', then output the character 12 13 14 15 16 17 18 19 20 public static void main(String[] args) ( / Type your code here. 7Explanation / Answer
import java.util.Scanner;
public class Main
{
private static Scanner scnr = new Scanner(System.in);
private static String text;
public static void main(String[] args)
{
System.out.println("Enter a sentence or phrase: ");
text=scnr.nextLine();
System.out.println("You entered: "+ text);
int count=getNumOfCharacters(text);
System.out.println();
System.out.println("Number of characters: " + count);
String modifiedstring = outputWithoutWhitespace();
System.out.println("String with no whitespace: " + modifiedstring);
}
private static String outputWithoutWhitespace()
{
text=text.trim().replaceAll(" ","");
return text;
}
private static int getNumOfCharacters(String t)
{
int count = 0;
for (char letter : t.toCharArray()){
count++;
}
return count;
}
}
/*SAMPLE 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.
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.