Use a TreeMap to sort the Words that are to be displayed, as usual, in the right
ID: 3838432 • Letter: U
Question
Use a TreeMap to sort the Words that are to be displayed, as usual, in the right column of the GridLayout.You will need to create a Comparator for the class Word.
Use a Regular Expression to verify that the passed to the constructor of a Word is three letters. Submitting the Project.
You should now have at least the following files to submit for this project:
Project4.java
Word.java-contains the regular expression
WordGUI.java
FileMenuHandler.java
WordComparator.java
IllegalWord212Exception.java
Make sure you do the codes:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Word { static final int WORD_SIZE = 3;
private static final Matcher matcher = null; String word; public Word(String word) { if (!isLegal(word)) throw new IllegalWordException("Invalid word: " + word); this.word = word; }
//fix this part public boolean isLegal(String w) { // Validate the String using regular expression here // (Refer to the Powerpoint on Regular Expressions) Pattern p; Matcher m; String Word_pattern= "^\w{0,3}$"; p = Pattern.compile(Word_pattern); m = p.matcher(w); return matcher.matches(); } public int compareTo(Word d) { return word.compareTo(d.word); } }
Explanation / Answer
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Word {
static final int WORD_SIZE = 3;
private static final Matcher matcher = null;
String word;
public Word(String word) {
if (!isLegal(word))
try {
throw new IllegalWordException("Invalid word: " + word);
} catch (IllegalWordException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.word = word;
}
// fix this part
public boolean isLegal(String w) {
// Validate the String using regular expression here // (Refer to the
// Powerpoint on Regular Expressions)
Pattern p;
Matcher m;
String Word_pattern = "\b[a-zA-Z]{3}\b";
p = Pattern.compile(Word_pattern);
m = p.matcher(w);
return m.matches();
}
public int compareTo(Word d) {
return word.compareTo(d.word);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Word [word=" + word + "]";
}
}
public class IllegalWordException extends Exception {
public IllegalWordException() {
// TODO Auto-generated constructor stub
}
public IllegalWordException(String string) {
// TODO Auto-generated constructor stub
super(string);
}
}
public class WordDemo {
public static void main(String[] args) {
Word word1 = new Word("Str");
System.out.println("Word with 3 chars :" + word1);
Word word2 = new Word("St");
System.out.println("Word with 2 chars :" + word2);
}
}
OUTPUT:
Word with 3 chars :Word [word=Str]
Word with 2 chars :Word [word=St]
IllegalWordException: Invalid word: St
at Word.<init>(Word.java:13)
at WordDemo.main(WordDemo.java:8)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.