CSC-112 – HW7 Complex Numbers Using RegEx

Due: Monday, March 18, 11:59pm

Make sure you post a GUI and email a gist before the due date. First thing Tuesday, in class, I’m going to discuss my solution to this problem.

We’ll finally put to rest Complex numbers with this HW7. HW7 will involve the actual Regular Expression (RegEx) implementation of the complex number string constructor. In HW6, many students created a GUI that looks like this, more or less:

This GUI supports entering complex numbers as strings. We will use regular expressions to perform the task of converting strings to complex numbers. The GUI will ultimately call the Complex constructor that takes a string input to produce the number.

Here’s some sample code we discussed in class that you can put into your constructor:

String regex = "^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(complexNumber);
if (matcher.find()) {
this.real = Double.parseDouble(matcher.group(0));
this.imag = 0;
return;
}

Some observations I made while building a solution:

  • Make sure you put a ^ in front of your regex’s and a $ at the end. This makes sure the entire string is matched and not just contained in the string! Note the sample above.
  • The code above checks for a string that is just a real number. You should have similar code for:
    • a string the is just an imaginary number
    • a string that is [+/-]?i ie. real part 0, imaginary part +/-1
    • a string the contains both a real part and an imaginary part
    • a string that contains a real part and an imaginary part that consists of just an i
  • If after going through all 5 checks for a valid complex number form, you didn’t do a return. Then the string passed in the constructor is gibberish, and so you should throw a RuntimeException.
  • If you plan on building a separate class that inherits from the Complex class, you’ll have to make some small changes to the Complex class:
    • remove the finals from real and imaginary properties.
    • Add simple setters for those properties.
    • the this.real and this.imag assignments in the sample code need to change to call the setters.

Please reference for additional help with HW7: