Darano

TextClass.java

Dec 2nd, 2018
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. public class TextClass {
  2.     private String text;
  3.  
  4.  
  5.     /*
  6.         Getter and Setter
  7.      */
  8.     public String getText() {
  9.         return text;
  10.     }
  11.  
  12.     public void setText(String text) {
  13.         this.text = text;
  14.     }
  15.  
  16.     /*
  17.         Constructors
  18.      */
  19.  
  20.     public TextClass(String text) {
  21.         this.text = text;
  22.     }
  23.  
  24.     public TextClass() {
  25.         this.text = "default";
  26.     }
  27.  
  28.     /*
  29.         Methods
  30.      */
  31.  
  32.     public int numberOfWords(String text) {
  33.         String trim = text.trim();
  34.         if (trim.isEmpty())
  35.             return 0;
  36.         return trim.split("\\s+").length; // \s regex metacharacter which finds whitespace character and split returns array of splitted words
  37.     }
  38.  
  39.     public int numberOfCharacters(String text) {
  40.         String trim = text.trim();
  41.         return trim.toCharArray().length;
  42.     }
  43.  
  44.     public int numberOfSentences(String text) {
  45.         String trim = text.trim();
  46.         if(trim.equals("")){
  47.             return 0;
  48.         }
  49.  
  50.         int i;
  51.         int counter = 0; //for counting sentences. Only the dot (.) seperates the sentences in this case
  52.  
  53.         for (i = 0; i < trim.length(); i++) {
  54.             if (trim.charAt(i) == '.')
  55.                 counter++;
  56.         }
  57.         if(counter == 0){
  58.             return counter += 1;
  59.         }
  60.         return counter;
  61.     }
  62.  
  63.     public boolean doesWordExist(String word, String text) {
  64.         if (text.indexOf(word) != -1) {
  65.             return true;
  66.         } else {
  67.             return false;
  68.         }
  69.     }
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment