6.15 Ch 6 Warm up: Text analyzer & modifier (Java)

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

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() 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:

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.

My code doesn’t seem to work. Here is what I have.

import java.util.Scanner;

public class TextAnalyzer {
   private static Scanner scanner=new Scanner(System.in);
   private static String text;
  
   public static void main (String [] args) {
        System.out.println(“Enter a sentence or phrase:”);
        System.out.println(“”);
        text = scanner.nextLine();
      
        System.out.println(“You entered: “+ text);
        System.out.println(“”);
       
        int count = getNumOfCharacters();
        System.out.println(“Number of characters: ” + count);
  
       
        String modifiedstring = outputWithoutWhitespace();
        System.out.println(“String with no whitespace: ” + modifiedstring);
        return;
      
    }

    private static String outputWithoutWhitespace()
    {
        text=text.trim().replaceAll(“s”,””);
        return text;             
    }

    private static int getNumOfCharacters()
    {     
       int i = 0;
       int length = 0;
       for (i = 0; i
          if (text.charAt(i) != ‘ ‘) || (text.charAt(i + 1) != ‘ ‘) {
             ++length;
          }
       }
         
     
    }

}



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *