Advertisement
advictoriam

Untitled

Jan 31st, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. //SOLUTION CHECKER BROKEN
  2. public class Sentence
  3. {
  4.    /**
  5.       Constructs a sentence.
  6.       @param text the text of the sentence. Words must be separated
  7.       by single spaces, and the sentence must end in a punctuation mark
  8.       (. ? !)
  9.    */
  10.    public Sentence(String text)
  11.    {
  12.       int n = text.length();
  13.       assert Character.toString(text.charAt(n-1)).matches("[.?!]");
  14.       assert (!text.contains("  "));
  15.       String punctuation = text.substring(n - 1, n);
  16.       words = text.substring(0, n - 1).split(" ");
  17.    }
  18.    
  19.    /**
  20.       Gets the number of words in this sentence.
  21.       @return the number of words
  22.    */
  23.    public int getWordCount()
  24.    {
  25.       return words.length;
  26.    }
  27.    
  28.    /**
  29.       Returns a word in this sentence.
  30.       @param the index of the word (must be at least 0 and less than the
  31.       word count)
  32.       @return the ith word
  33.    */
  34.    public String getWord(int i)
  35.    {
  36.       return words[i];
  37.    }
  38.    
  39.    public String toString()
  40.    {
  41.       String r = "";
  42.       for (String w : words)
  43.       {
  44.          if (r.length() > 0) r += " ";
  45.          r += w;
  46.       }
  47.       return r + punctuation;
  48.    }
  49.    
  50.    private String[] words;
  51.    private String punctuation;
  52.    
  53.    /*
  54.       The following method checks your constructor. We use the exception
  55.       handling mechanism (see chapter 11) to determine whether (a) the
  56.       constructor completed normally, (b) your code used an assertion to
  57.       check a precondition violation, or (c) you failed to use an
  58.       assertion and some other exception occurred.
  59.    */
  60.    
  61.    public static String check(String text)
  62.    {
  63.       try
  64.       {
  65.          Sentence s = new Sentence(text);
  66.          return "Constructor completed normally";      
  67.       }
  68.       catch (AssertionError error)
  69.       {
  70.          return "Precondition violation detected";
  71.       }
  72.       catch (Exception exception)
  73.       {
  74.          return "Exception in constructor";
  75.       }
  76.    }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement