3 votes

Comment prendre l'entrée de l'utilisateur pour un nombre complexe

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());  
            }   
        }

Je ne suis pas en mesure de recevoir l'entrée correcte de l'utilisateur. Je veux être en mesure de recevoir 2+4i dans le premier nombre complexe et 4+5i en second nombre complexe à partir de l'entrée de l'utilisateur. Mais cela ne fonctionne pas.

2voto

Jason Points 2377

Au début de votre méthode principale :

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

Ensuite, dans 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);

Vous voudrez probablement ajouter un traitement des erreurs si les données saisies par l'utilisateur ne correspondent pas au modèle requis (sinon, l'option real y imaginary seront toutes deux égales à 0).

0voto

Ajouter la méthode suivante dans la classe 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]));
}

et ensuite Au lieu de premierComplexe=get.nextDouble() ; utilisez firstComplex=getComplexNumber(get) ; gérer les exceptions également

0voto

Alykoff Gali Points 769

Vous devez obtenir le chemin réel et imaginaire du nombre complexe.

En faisant quelques changements dans votre code J'ai ce résultat :

La logique principale est la suivante :

private final static Pattern PATTERN = Pattern.compile("(.*)([+-])(.*)i");
// ...
String complexInput = get.next();
final Matcher matcher = PATTERN.matcher(complexInput);
if (matcher.find()) {
    final double imgSign = matcher.group(2).equals("+") ? 1D : -1D;
    final double real = Double.parseDouble(matcher.group(1));
    final double img = Double.parseDouble(matcher.group(3));
    return new Complex(real, imgSign * img);
}

Tous les codes :

public class Driver {

    private final static Pattern PATTERN = Pattern.compile("(.*)([+-])(.*)i");
    private static final int CHOICE_EXIT = 5;
    private static final int CHOICE_ADD = 1;

    public static void main(String[] args) {
        Scanner get = new Scanner(System.in);

        int choice;
        Complex c1;
        Complex c2;

        while (true) {
            try {
                printInfoAboutChoice();
                choice = get.nextInt();
                if (choice == CHOICE_EXIT) {
                    break;
                }
                System.out.println("Enter first complex number: ");
                c1 = getComplexFromString(get.next());

                System.out.println("Enter Second complex number: ");
                c2 = getComplexFromString(get.next());
            } catch (RuntimeException e) {
                System.err.println(e.getMessage());
                continue;
            }

            switch (choice) {
                case CHOICE_ADD: {
                    Complex c3 = c1.add(c2);
                    System.out.println(c3.toString());
                }
                // TODO others methods...
            }
        }
    }

    private static Complex getComplexFromString(String complexInput) throws IllegalFormatException {
        final Matcher matcher = PATTERN.matcher(complexInput);
        if (matcher.find()) {
            final double imgSign = matcher.group(2).equals("+") ? 1D : -1D;
            final double real = Double.parseDouble(matcher.group(1));
            final double img = Double.parseDouble(matcher.group(3));
            return new Complex(real, imgSign * img);
        }
        throw new IllegalArgumentException("Bad complex number input");
    }

    private static void printInfoAboutChoice() {
        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");
    }
}

0voto

Gurwinder Singh Points 31991

Voici quelque chose si vous avez des pièces entières. Veuillez modifier pour les doubles.

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

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X