Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a complex number in java

Tags:

java

I'm fairly new to java programming, and i'm writing a "Complex" class so i can learn a bit about OOP.

While writing a read() method to get the user input on a Complex number, i ran into a problem. Currently, the user has to input 2 numbers separated by spaces, and those will be respectively the real and imaginary parts. But if they enter something like "3 + 4i" or "3.23+4.1i", either the whole thing is ignored or only the first number is read.

I want to make this method better by allowing the user to input the number in any of those formats, plus allowing them to simply enter something like "3i" instead of "0 + 3i".

What i found while researching usually involved patterns or Double.parseDouble, neither of which I got to work for my case.

My question is: How can i detect those characters so i can parse the complex number properly?

P.S: Here's the bit of my method that reads user input for now

if(userIn.hasNextDouble())
{
    this.real=userIn.nextDouble();
}

if(userIn.hasNextDouble())
{
    this.imag=userIn.nextDouble();
}
like image 695
Pedro Freitas Avatar asked Apr 28 '26 06:04

Pedro Freitas


1 Answers

Read a String instead of a Double. Then:

boolean firstPositive = true;
boolean secondPositive = true;
if (s.charAt(0) == '-')     // See if first expr is negative
    firstPositive = false;
if (s.substring(1).contains("-"))
    secondPositive = false;
String[] split = s.split("[+-]");
if (split[0].equals("")) {  // Handle expr beginning with `-`
    split[0] = split[1];
    split[1] = split[2];
}
double realPart = 0;
double imgPart = 0;
if (split[0].contains("i")) // Assumes input is not empty
    imgPart = Double.parseDouble((firstPositive ? "+" : "-") + split[0].substring(0,split[0].length - 1));
else
    realPart = Double.parseDouble((firstPositive ? "+" : "-") + split[0]);
if (split.length > 1) {     // Parse second part of expr if it exists
    if (split[1].contains("i"))
        imgPart = Double.parseDouble((secondPositive ? "+" : "-") + split[1].substring(0,split[1].length - 1));
    else
        realPart = Double.parseDouble((secondPositive ? "+" : "-") + split[1]);
}
// Use realPart and imgPart ...
System.out.println(realPart + (imgPart < 0 ? "" : "+") + imgPart + "i");

If you only want to support Integers then change Double.parseDouble to Integer.parseInt.

It handles anything from 3 to -5.123i to -5-631231.2123123i

like image 156
M. Shaw Avatar answered Apr 30 '26 20:04

M. Shaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!