如何获取复杂数字的用户输入

时间:2016-11-14 21:32:32

标签: java

public class Complex {

    private double real;
    private double imaginary;

    public Complex(){
        this.real=0;
        this.imaginary=0;
    }

    public Complex(double real,double imaginary){
        this.real=real;
        this.imaginary=imaginary;
    }

    public double getReal() {
        return real;
    }

    public void setReal(double real) {
        this.real = real;
    }

    public double getImaginary() {
        return imaginary;
    }

    public void setImaginary(double imaginary) {
        this.imaginary = imaginary;
    }

    public Complex add(Complex num){
        double r=this.real+num.real;
        double i=this.imaginary + num.imaginary;
        Complex s= new Complex(r,i);
        return s;

    }

    public Complex sub(Complex num){
        double r= this.real- num.real;
        double i= this.imaginary - num.imaginary;
        Complex s= new Complex(r,i);
        return s;
    }

    public Complex mul(Complex num){
        double r= this.real*num.real - this.imaginary*num.imaginary;
        double i= this.real*num.imaginary+this.imaginary*num.real;

        Complex s=new Complex(r,i);
        return s;
    }

    public Complex div(Complex num){
        double r= this.real/num.real- this.imaginary/num.imaginary;
        double i = this.real/num.imaginary+this.imaginary/num.real;

        Complex s=new Complex(r,i);
        return s;
    }

    public String toString(){
        //double x=this.real + this.imaginary;
        //return " "+x;

        return this.real+" + "+this.imaginary+"i";
    }
}



import java.util.*;
import java.math.*;

public class Driver {

    public static final double i=Math.sqrt(-1);

    public static void main(String[] args) {

        Scanner get=new Scanner(System.in);

        int choice;
        double firstComplex;
        double secondComplex;

        //Complex c1 = new Complex(3.0,4.2);
        //Complex c2 = new Complex(-12.2,3.4);

        //Complex c4 =c1.sub(c2);
        //Complex c5 =c1.mul(c2);
        //Complex c6 =c1.div(c2);

        while(true){
            System.out.println("Please type your choice and enter : ");

            System.out.println("1.Add Two Complex Numbers");
            System.out.println("2.Substract Two Complex Numbers");
            System.out.println("3.Multiply Two Complex Numbers");
            System.out.println("4.Divide Two Complex Numbers");
            System.out.println("5.Exit Program");

            choice= get.nextInt();

            switch(choice){
                case 1 :
                    System.out.println("Enter first complex number: ");

                    firstComplex=get.nextDouble();

                    System.out.println("Enter Second complex number: ");

                    secondComplex=get.nextDouble();

                    Complex c1 = new Complex(firstComplex,firstComplex);
                    Complex c2 = new Complex(secondComplex,secondComplex);
                    Complex c3 =c1.add(c2);

                    System.out.println(c3.toString());  
            }   
        }

我无法收到正确的用户输入。我希望能够从用户输入中接收第一个复数中的2+4i和第二个复数中的4+5i。但它没有用。

4 个答案:

答案 0 :(得分:2)

在主要方法的开头:

    Pattern p = Pattern.compile("(.*)([+-].*)i");
    double real, imaginary;

然后在case 1:

    System.out.println("Enter first complex number: ");

    real = 0.0;
    imaginary = 0.0;
    Matcher m = p.match(get.nextLine()); // read the user input as a string
    if (m.matches()) { // if the user input matches the required pattern
        real = Double.parseDouble(m.group(1)); // extract the real part
        imaginary = Double.parseDouble(m.group(2)); // extract the imaginary part
    }
    Complex c1 = new Complex(real, imaginary); // build the Complex object

    System.out.println("Enter Second complex number: ");

    real = 0.0;
    imaginary = 0.0;
    Matcher m = p.match(get.nextLine());
    if (m.matches()) {
        real = Double.parseDouble(m.group(1));
        imaginary = Double.parseDouble(m.group(2));
    }
    Complex c2 = new Complex(real, imaginary);

    Complex c3 =c1.add(c2);

如果用户的输入与所需模式不匹配,您可能想要添加一些错误处理(否则realimaginary都将为0)

答案 1 :(得分:0)

在Driver类

中添加以下方法
public static Complex getComplexNumber(final Scanner get){
        String firstComplex=get.nextLine();
        String[] arr = firstComplex.split("[-+]i");
        return new Complex(Double.parseDouble(arr[0]),Double.parseDouble(arr[1]));
}

然后而不是 firstComplex = get.nextDouble(); 使用 firstComplex = getComplexNumber(获取); 处理异常

答案 2 :(得分:0)

你需要获得复数的真实和虚构路径。

通过在代码中进行一些更改,我得到了以下结果:

主要逻辑是:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ajouter_facture);

    btndate = (Button) findViewById(R.id.dateFacture);
    bundle = getIntent().getExtras();
    BundleNature = bundle.getString("Nature");
    Type = bundle.getString("Type");
    if (Type.equals("AddButton")){
        setTitle("Ajouter Facture");
        generateNumFacture();
    }
    if (Type.equals("OpenButton")){
        setTitle("Modifier Facture");
        getFacture();
        getLigneFacture();

    }

    this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    Typeface type = Typeface.createFromAsset(getAssets(),"Sansation_Bold.ttf");

    left1 = (TextView) findViewById(R.id.left_text1);
    left1.setTypeface(type);
    left2 = (TextView) findViewById(R.id.left_text2);
    left2.setTypeface(type);
    right1 = (TextView) findViewById(R.id.montantTotal);
    right1.setTypeface(type);
    right2 = (TextView) findViewById(R.id.montantTotalFacture);
    right2.setTypeface(type);
    lv = (ListView) findViewById(R.id.lv_liste_lignefacture);

    lv.setOnTouchListener(new ListView.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    // Disallow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    break;

                case MotionEvent.ACTION_UP:
                    // Allow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    break;
            }

            // Handle ListView touch events.
            v.onTouchEvent(event);
            return true;
        }
    });
    adapter = new LigneFactureAdapter(this,ligneFactList);
    ligneFactList.clear();
    ligneComFact.clear();


    final Calendar cal = Calendar.getInstance();
    year_x = cal.get(Calendar.YEAR);
    month_x = cal.get(Calendar.MONTH);
    day_x = cal.get(Calendar.DAY_OF_MONTH);
    showDialogOnClick();

    et_NumFacture = (EditText) findViewById(R.id.numFactureTV);
    et_NumCommande = (EditText) findViewById(R.id.numCFactTV);
    et_CodeClient = (EditText) findViewById(R.id.codeClientFactTV);
    et_MatriculeEmploye = (EditText) findViewById(R.id.matriculetEmployeFactTV);
    et_Etat = (Spinner) findViewById(R.id.etatPaiFactTV);
    et_Remise = (EditText) findViewById(R.id.remiseFactTV);
    et_PourBoir = (EditText) findViewById(R.id.pourBoirTF);
    tvMontant = (TextView) findViewById(R.id.montantTotalFacture);
    tvTotal = (TextView) findViewById(R.id.montantTotal);
    btnAddLignFact = (ImageButton) findViewById(R.id.btnAjouterLigneFacture);

    addLigneFactureCommande();
    getCodeClient();
    getMatriculeEmploye();
    populateEtatLiv();
    AddLigneFactureButton();
    updatePrixQuantite();
    updateRemisePourBoire();
    deleteLigneFacture();
}

所有代码:

  <activity
        android:name="formulaires.AjouterFactureActivity"
        android:configChanges="orientation|screenSize"
        android:label="@string/title_activity_ajouter_facture"
        android:theme="@style/Theme.AppCompat.Light"
        android:windowSoftInputMode="stateHidden|adjustResize" >
    </activity>

答案 3 :(得分:0)

如果你有整数部分,这是一些东西。请修改双打。

Complex c1;
Scanner sline = new Scanner(System.in);
Pattern p = Pattern.compile("(\+|-){0,1}\\d+[ ]*(\+|-)[ ]*(i\\d+|\\d+i)");
if(sline.hasNext(p)) {
    String str = sline.next(p).replace("+"," +").replace("-"," -");
    Scanner sc = new Scanner(str);
    int r = sc.nextInt();
    int i = Integer.parseInt(sc.next().replace('i',''));
    c1 = new Complex(r, i);
}
相关问题