找到你要的答案

Q:Parsing a complex number in java

Q:解析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();
}

我对java编程相当新,我写一个“复杂”的类,所以我可以学一点关于OOP。

在写read()方法得到一个复数的用户输入,我遇到了一个问题。目前,用户必须输入2个数字分隔的空间,而这些将分别为实部和虚部。但如果他们进入类似“3 + 4I”或“3.23+4.1i”,要么是忽视或只有第一个数字阅读。

我想通过允许用户输入任何这些格式的数量使该方法更好,加上允许他们只需输入类似“3I”代替“0+3I”。

我发现在研究通常涉及的模式或double.parsedouble,这既不是我要为我工作。

我的问题是:我怎样才能检测到这些字符,以便我可以正确地分析复杂的数字?

这是我的方法的一部分,现在读取用户输入

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

if(userIn.hasNextDouble())
{
    this.imag=userIn.nextDouble();
}
answer1: 回答1:

I took the liberty to do this. Just give it a try. It does not check for incorrect input. It will create the complex numbers, store them in an ArrayList and output the newly created numbers to the screen.

import java.util.ArrayList;
import java.util.Scanner;

public class Complex {
    Double real=0d;
    Double complex=0d;
    Complex(Double real, Double complex){
        this.real=real;
        this.complex=complex;
    }
    Complex(){
    }
    public void setReal(Double real){
        this.real=real;
    }
    public void setComplex(Double complex){
        this.complex=complex;
    }
    public Double getReal(){
        return real;
    }
    public String getComplex(){
        return complex+"i";
    }
    public String toString(){
        if (real==0d)
            return complex+"i";
        else if (complex==0d)
            return real+"";
        else
        return real+" + "+complex+"i";
    }
    static ArrayList<Complex> complexList=new ArrayList<Complex>();
    public static void createComplex(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("Type the complex numbers; Type Done to finish!");
        String x=scanner.next();

        while (!x.equals("Done")){
           // System.out.println(x);
            Complex no=new Complex();
            //check if the user has inputted only one number
            if (!x.contains("+")&&!x.contains("i")){
                no.setReal(Double.parseDouble(x));
                x= scanner.next();
                //ask for the second number; no wrong input checks
                no.setComplex(Double.parseDouble(x));
            }
            //check if the user inputted something like 123.3i
            else if (!x.contains("+")&&x.contains("i")){
                //create the complex number; replace i with ""
                x=x.replace("i","");

               // System.out.println(x);
                no.setComplex(Double.parseDouble(String.valueOf(x)));
            }
            else{
               //else remove the + sign and create a complex number
               //input like 123.3+32i
               //no wrong input checks
               x= x.replaceAll("\\s+","");
                String[] tokens = x.split("\\+");
                no.setReal(Double.parseDouble(String.valueOf(tokens[0])));
                tokens[1]=tokens[1].replace("i","");
                no.setComplex(Double.parseDouble(String.valueOf(tokens[1])));
            }
            //ask for next input until Done is typed
            x=scanner.next();
            complexList.add(no);
        }
    }

    public static void main(String[] args) {
        createComplex();
        for (Complex x:complexList){
            System.out.println(x.toString());
        }
    }

}

Test input & output:

Type the complex numbers; Type Done to finish!
123.123
412231.21
123i
9i
1+9i
123+12312.3i
Done
123.123 + 412231.21i
123.0i
9.0i
1.0 + 9.0i
123.0 + 12312.3i

我冒昧地这样做。只要尝试一下。它不检查输入错误。它将创造出复杂的数字,它们存储在一个ArrayList和新创建的数字输出到屏幕。

import java.util.ArrayList;
import java.util.Scanner;

public class Complex {
    Double real=0d;
    Double complex=0d;
    Complex(Double real, Double complex){
        this.real=real;
        this.complex=complex;
    }
    Complex(){
    }
    public void setReal(Double real){
        this.real=real;
    }
    public void setComplex(Double complex){
        this.complex=complex;
    }
    public Double getReal(){
        return real;
    }
    public String getComplex(){
        return complex+"i";
    }
    public String toString(){
        if (real==0d)
            return complex+"i";
        else if (complex==0d)
            return real+"";
        else
        return real+" + "+complex+"i";
    }
    static ArrayList<Complex> complexList=new ArrayList<Complex>();
    public static void createComplex(){
        Scanner scanner=new Scanner(System.in);
        System.out.println("Type the complex numbers; Type Done to finish!");
        String x=scanner.next();

        while (!x.equals("Done")){
           // System.out.println(x);
            Complex no=new Complex();
            //check if the user has inputted only one number
            if (!x.contains("+")&&!x.contains("i")){
                no.setReal(Double.parseDouble(x));
                x= scanner.next();
                //ask for the second number; no wrong input checks
                no.setComplex(Double.parseDouble(x));
            }
            //check if the user inputted something like 123.3i
            else if (!x.contains("+")&&x.contains("i")){
                //create the complex number; replace i with ""
                x=x.replace("i","");

               // System.out.println(x);
                no.setComplex(Double.parseDouble(String.valueOf(x)));
            }
            else{
               //else remove the + sign and create a complex number
               //input like 123.3+32i
               //no wrong input checks
               x= x.replaceAll("\\s+","");
                String[] tokens = x.split("\\+");
                no.setReal(Double.parseDouble(String.valueOf(tokens[0])));
                tokens[1]=tokens[1].replace("i","");
                no.setComplex(Double.parseDouble(String.valueOf(tokens[1])));
            }
            //ask for next input until Done is typed
            x=scanner.next();
            complexList.add(no);
        }
    }

    public static void main(String[] args) {
        createComplex();
        for (Complex x:complexList){
            System.out.println(x.toString());
        }
    }

}

测试输入输出:

Type the complex numbers; Type Done to finish!
123.123
412231.21
123i
9i
1+9i
123+12312.3i
Done
123.123 + 412231.21i
123.0i
9.0i
1.0 + 9.0i
123.0 + 12312.3i
answer2: 回答2:

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

读一个字符串而不是一个双。然后:

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");

如果你只想支持整数,然后改变double.parsedouble到integer.parseint。

它可以处理任何从3到-5.123i到-5-631231.2123123i

answer3: 回答3:

Idea for an algorithm easy to implement that might work :

  1. Read the line //ex: "3.23 + 4i" --- ex2: "3.23" --- ex3: "4i"
  2. Get rid of all spaces //ex: "3.23+4i" --- ex2: "3.23" --- ex3: "4i"
  3. Split with "+" char //ex: ["3.23","4i"] --- ex2: ["3.23"] --- ex3: ["4i"]

    4.1 If one element in array => find the result by just testing if it ends by "i" (fairly trivial)

    4.2 If two element in the array =>

    • 4.2.1 verify if the first element ends by i and read it accordingly (fairly trivial)

    • 4.2.2 verify if the first element ends by i and read it accordingly (fairly trivial)

I think all step are relatively easy to implement, but if you have a question as to how to do it, don't hesitate. I suppose there are ways to do it more elegantly with patterns and so on, but sometime, the simplest things works too (if you don't have performance issues).

Godd luck,

Mathias

一个易于实现的算法的思想:

  1. Read the line //ex: "3.23 + 4i" --- ex2: "3.23" --- ex3: "4i"
  2. Get rid of all spaces //ex: "3.23+4i" --- ex2: "3.23" --- ex3: "4i"
  3. 分裂与“+”字符/前:[“3.23”、“4I”]——EX2:[“3.23”]——EX3:[“4I”]

    4.1如果在阵列= & gt一元;发现结果只是测试如果结束由“我”(非常小的)

    4.2如果在阵列= & gt二元;

    • 4.2.1验证如果第一单元结束我读它因此(非常小的)

    • 4.2.2验证如果第一单元结束我读它因此(非常小的)

我认为所有的步骤都比较容易实现,但如果你有一个问题,就如何做到这一点,不要犹豫。我想有方法可以更优雅的模式等,但有时,最简单的事情也工作(如果你没有性能问题)。

好的运气,

马蒂亚斯

answer4: 回答4:

In a first try do:

String test="3+4i";
    String[] temp=null;
    String realString=null;
    String imagString=null;

    if(test.contains("+")){
        temp=test.split("\\+");

    }
    else if(test.contains("-")){
        temp=test.split("-");
    }
    if(temp[0].contains("i")){
        realString=temp[1];
        imagString=temp[0].trim().split("i")[0];
    }
    else{
        realString=temp[0];
        imagString=temp[1].trim().split("i")[0];
    }

     System.out.println(realString+ " "  +imagString);

It is just a first try to help you. You ll have to adapt it to accept numbers like "-3,14i + 12". And you'll still have to parse the string into the right format.

在第一次尝试做:

String test="3+4i";
    String[] temp=null;
    String realString=null;
    String imagString=null;

    if(test.contains("+")){
        temp=test.split("\\+");

    }
    else if(test.contains("-")){
        temp=test.split("-");
    }
    if(temp[0].contains("i")){
        realString=temp[1];
        imagString=temp[0].trim().split("i")[0];
    }
    else{
        realString=temp[0];
        imagString=temp[1].trim().split("i")[0];
    }

     System.out.println(realString+ " "  +imagString);

It is just a first try to help you. You ll have to adapt it to accept numbers like "-3,14i + 12". And you'll still have to parse the string into the right format.

answer5: 回答5:

I understand that it's a learning task and you want to implement it by yourself, but if other people will read this question it's much better to use Apache Commons Math library. It has a ComplexFormat class which can parse complex numbers:

String str = "3.23+4.1i";
Complex c = new ComplexFormat().parse(str);
double realPart = c.getReal();
double imaginaryPart = c.getImaginary();

我明白,这是一个学习的任务,你想实现它自己,但如果其他人会阅读这个问题最好使用Apache Commons数学库。它有一个complexformat类,可以解析复杂的数字:

String str = "3.23+4.1i";
Complex c = new ComplexFormat().parse(str);
double realPart = c.getReal();
double imaginaryPart = c.getImaginary();
java