Advertisement
advictoriam

Untitled

Jan 25th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. /**
  4.    This class models a sentence.
  5. */
  6. public class Sentence
  7. {
  8.    private ArrayList<String> words;
  9.  
  10.    /**
  11.       Construct a sentence with a given text.
  12.       @param text the sentence. The text ends in a
  13.       punctuation mark which is not stored.
  14.    */
  15.    public Sentence(String text)
  16.    {
  17.       words = new ArrayList<String>();
  18.       String word = "";
  19.       for(int i = 0; i < text.length(); i++)
  20.       {
  21.          if(text.charAt(i) == ' ' || !(Character.isLetter(text.charAt(i))))
  22.          {
  23.             words.add(word);
  24.             word = "";
  25.          }
  26.          else {word += text.charAt(i);}
  27.       }
  28.    }
  29.  
  30.    /**
  31.       Get the ith word in the sentence.
  32.       @return the ith word
  33.    */
  34.    public String getWord(int i)
  35.    {
  36.       return words.get(i);
  37.    }
  38.  
  39.    /**
  40.       Get the number of words in the sentence.
  41.       @return the number of words
  42.    */
  43.    public int getCount()
  44.    {
  45.       return words.size();
  46.    }  
  47.  
  48.    // This method is used for checking your work. Do not modify it
  49.  
  50.    public static String check(String sent)
  51.    {
  52.       Sentence aSentence = new Sentence(sent);
  53.       return aSentence.getWord(aSentence.getCount() - 1);
  54.    }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement