Looking for Feedback on My Java Complex Number Class

0
12
Asked By CodeWizard92 On

Hey everyone! I'm relatively new to coding and this is my first major project. I'm working on an app that allows users to input polynomial equations and get the exact solutions back, or as close as possible to the precision that computers can achieve.

To accomplish this, I've created my own Complex number class, since Java doesn't have a built-in one and the IDE my teacher provided can only use built-in libraries. Here's what I need this class to do: find the cube root of a complex number, allow adding a real number to a complex number, multiply two complex numbers together, and provide a String representation when printed.

I've pasted my code below. I'd appreciate any feedback on how to improve its readability or simplify it. Thanks!

2 Answers

Answered By TechGuru33 On

Overall, it looks pretty good! The implementation is clear and you've made an immutable class, which is great. Here are a couple of suggestions:

First, the 'cbrt' method returning a double seems inconsistent with your other methods, which always return a Complex instance. It might be better to stick to the object-oriented approach.

Second, if you need higher precision in your calculations, consider using Java's BigDecimal class. Just keep in mind that it might slow down your performance a bit, but it could be worthwhile for accuracy. Good luck!

Answered By MathWhiz246 On

Your class looks solid for a beginner! A couple of things to think about:
First, consider that someone might want to use your class to perform actual complex math. You might want to prioritize implementing methods that take a Complex number directly. For example, you can have a multiply method that accepts a double and just calls the Complex one. Something like this: `public Complex multiply(double other) { return multiply(Complex.of(other)); }`.

Also, instead of directly using 'new Complex()', consider having a static method like `Complex.of(double)`, which is becoming standard in Java. And definitely include equals and hashCode methods; they are essential if you want to use your objects in collections.

Lastly, real and imaginary could be shortened to 'r' and 'i', which would make the mathematical operations cleaner and easier to read. Keep it up!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.