Partage
  • Partager sur Facebook
  • Partager sur Twitter

Calculatrice

    10 février 2022 à 22:20:01

    Bonjour à tous, 

    j'ai pour projet de coder une calculatrice en langage java en prenant celle d'un iphone comme modèle. Je précise que je suis en 2e année d'informatique. Pour le coup la calculatrice n'ai aucuns problèmes jusqu'à ce que l'on essaye d'effectuer une opération à partir d'un résultat issue d'une précédente opération (en gros on ne peut pas faire 2 opérations à la suite, ce qui est bien dommage :/)
    Pourtant j'ai beau lire et relire mon code je ne vois vraiment pas pourquoi ca ne fonctionne pas. Si quelqu'un pourrait m'aider svp ca serait un immense plaisir :)

    Le code entier ci-dessous est long mais je préfère tout vous mettre pour que vous puissiez essayer avec vos IDE. Mais sinon l'erreur est censé se trouver vers la 2e moitié, entre la partie bouton + et bouton x²

    import java.awt.*;
    
    public class Calculatrice extends JFrame implements ActionListener {
    
    // Boutons entier
    
    private JButton bt0 = new JButton ("0");
    
    private JButton bt1 = new JButton ("1");
    
    private JButton bt2 = new JButton ("2");
    
    private JButton bt3 = new JButton ("3");
    
    private JButton bt4 = new JButton ("4");
    
    private JButton bt5 = new JButton ("5");
    
    private JButton bt6 = new JButton ("6");
    
    private JButton bt7 = new JButton ("7");
    
    private JButton bt8 = new JButton ("8");
    
    private JButton bt9 = new JButton ("9");
    
    // Pour afficher les boutons
    
    private JPanel pan = new JPanel();
    
    // Fonts
    
    Font fButton = new Font("Arial", Font.BOLD, 18); // Taille du texte des boutons
    
    Font fResultat = new Font("Arial", Font.BOLD, 40); // Taille du résultat
    
    Font fErreur = new Font("Arial", Font.BOLD, 20); // Taille du texte de l'erreur
    
    // Labels
    
    private JLabel lab1 = new JLabel(""); // Affichage des entiers
    
    private JLabel lab2 = new JLabel(""); // Affichage des opérateurs
    
    private JLabel lab3 = new JLabel(""); // Affichage des entiers aprés l'opérateur
    
    private JLabel lab4 = new JLabel(""); // Affichage du resultat
    
    private JLabel lab5 = new JLabel(""); // Erreur 1 : (Erreur de syntaxe)
    
    private JLabel lab6 = new JLabel(""); // Erreur 2 : (désignation de l'erreur)
    
    // Opérateurs
    
    private JButton bt10 = new JButton ("+");
    
    private JButton bt11 = new JButton ("=");
    
    private JButton bt12 = new JButton ("-");
    
    private JButton bt13 = new JButton ("X");
    
    private JButton bt17 = new JButton("÷");
    
    private JButton bt15 = new JButton ("%");
    
    private JButton bt16 = new JButton("x²");
    
    private JButton bt18 = new JButton(",");
    
    // Supprimer
    
    private JButton bt14 = new JButton ("AC");
    
    // Résultat
    
    private double resultat;
    
    DecimalFormat df = new DecimalFormat("0.00000");
    
    public Calculatrice() {
    
    /* Titre de la fenêtre */
    
    this.setTitle("Calculatrice");
    
    this.setBounds(500, 300, 300, 500);
    
    /* Ne pas redimenssionnez la fenêtre (avec la souris) */
    
    this.setResizable(false);
    
    /* Fermer la fenêtre */
    
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    /* Couleur de fond d'écran de la fenêtre */
    
    pan.setBackground(Color.darkGray);
    
    /* Ne Location relative à  null */
    
    this.setLocationRelativeTo(null);
    
    /* Pas de disposition */
    
    this.pan.setLayout(null);
    
    /* Label 1 (Affichage des entiers) */
    
    this.lab1.setBounds(5, 5, 300, 40);
    
    this.lab1.setForeground(Color.WHITE);
    
    this.lab1.setFont(fResultat);
    
    this.pan.add(lab1);
    
    /* Label 2 (Affichage des opérateurs)  */
    
    this.lab2.setBounds(5, 50, 150, 40);
    
    this.lab2.setForeground(Color.WHITE);
    
    this.lab2.setFont(fResultat);
    
    this.pan.add(lab2);
    
    /* Label 3 (Affichage des entiers après l'opérateur) */
    
    this.lab3.setBounds(5, 95, 300, 40);
    
    this.lab3.setForeground(Color.WHITE);
    
    this.lab3.setFont(fResultat);
    
    this.pan.add(lab3);
    
    /* Label 4 (Affichage du résultat) */
    
    this.lab4.setBounds(5, 5, 600, 40);
    
    this.lab4.setForeground(Color.WHITE);
    
    this.lab4.setFont(fResultat);
    
    this.pan.add(lab4);
    
    /* Label 5 (Erreur 1 : "Erreur de syntaxe : ") */
    
    this.lab5.setBounds(5, 5, 600, 40);
    
    this.lab5.setForeground(Color.YELLOW);
    
    this.lab5.setFont(fErreur);
    
    this.pan.add(lab5);
    
    /* Label 6 (Erreur 2 : (désignation de l'erreur)) */
    
    this.lab6.setBounds(5, 60, 600, 40);
    
    this.lab6.setForeground(Color.YELLOW);
    
    this.lab6.setFont(fErreur);
    
    this.pan.add(lab6);
    
    /* 1ere ligne : AC x² ÷ â—€ */
    
    // Bouton AC
    
    this.bt14.setBounds(0, 160, 75, 60);
    
    this.bt14.setBackground(Color.GRAY); // Fond du bouton
    
    this.bt14.setForeground(Color.WHITE); // Couleur du texte
    
    this.bt14.setFont(fButton); // Taille du texte
    
    this.bt14.addActionListener(this);
    
    this.pan.add(bt14);
    
    // Bouton x²
    
    this.bt16.setBounds(75, 160, 75, 60);
    
    this.bt16.setBackground(Color.GRAY);
    
    this.bt16.setForeground(Color.WHITE);
    
    this.bt16.setFont(fButton);
    
    this.bt16.addActionListener(this);
    
    this.pan.add(bt16);
    
    // Bouton %
    
    this.bt15.setBounds(145, 160, 75, 60);
    
    this.bt15.setBackground(Color.GRAY);
    
    this.bt15.setForeground(Color.WHITE);
    
    this.bt15.setFont(fButton);
    
    this.bt15.addActionListener(this);
    
    this.pan.add(bt15);
    
    // Bouton â—€
    
    this.bt17.setBounds(215, 160, 75, 60);
    
    this.bt17.setBackground(new Color(255, 140, 0)); // Fond orange
    
    this.bt17.setForeground(Color.WHITE);
    
    this.bt17.setFont(fButton);
    
    this.bt17.addActionListener(this);
    
    this.pan.add(bt17);
    
    /* 2eme ligne : 7 8 9 X */
    
    // Bouton 7
    
    this.bt7.setBounds(0, 220, 75, 60);
    
    this.bt7.setBackground(Color.GRAY);
    
    this.bt7.setForeground(Color.WHITE);
    
    this.bt7.setFont(fButton);
    
    this.bt7.addActionListener(this);
    
    this.pan.add(bt7);
    
    // Bouton 8
    
    this.bt8.setBounds(75, 220, 75, 60);
    
    this.bt8.addActionListener(this);
    
    this.bt8.setBackground(Color.GRAY);
    
    this.bt8.setForeground(Color.WHITE);
    
    this.bt8.setFont(fButton);
    
    this.pan.add(bt8);
    
    // Bouton 9
    
    this.bt9.setBounds(145, 220, 75, 60);
    
    this.bt9.setBackground(Color.GRAY);
    
    this.bt9.setForeground(Color.WHITE);
    
    this.bt9.setFont(fButton);
    
    this.bt9.addActionListener(this);
    
    this.pan.add(bt9);
    
    // Bouton X
    
    this.bt13.setBounds(215, 220, 75, 60);
    
    this.bt13.setBackground(new Color(255, 140, 0));
    
    this.bt13.setForeground(Color.WHITE);
    
    this.bt13.setFont(fButton);
    
    this.bt13.addActionListener(this);
    
    this.pan.add(bt13);
    
    /* 3eme ligne : 4 5 6 - */
    
    // Bouton 4
    
    this.bt4.setBounds(0, 280, 75, 60);
    
    this.bt4.setBackground(Color.GRAY);
    
    this.bt4.setForeground(Color.WHITE);
    
    this.bt4.setFont(fButton);
    
    this.bt4.addActionListener(this);
    
    this.pan.add(bt4);
    
    /* Bouton 5 */
    
    this.bt5.setBounds(75, 280, 75, 60);
    
    this.bt5.setBackground(Color.GRAY);
    
    this.bt5.setForeground(Color.WHITE);
    
    this.bt5.setFont(fButton);
    
    this.bt5.addActionListener(this);
    
    this.pan.add(bt5);
    
    /* Bouton 6 */
    
    this.bt6.setBounds(145, 280, 75, 60);
    
    this.bt6.setBackground(Color.GRAY);
    
    this.bt6.setForeground(Color.WHITE);
    
    this.bt6.setFont(fButton);
    
    this.bt6.addActionListener(this);
    
    this.pan.add(bt6);
    
    // Bouton -
    
    this.bt12.setBounds(215, 280, 75, 60);
    
    this.bt12.setBackground(new Color(255, 140, 0));
    
    this.bt12.setForeground(Color.WHITE);
    
    this.bt12.setFont(fButton);
    
    this.bt12.addActionListener(this);
    
    this.pan.add(bt12);
    
    /* 4eme ligne : 1 2 3 + */
    
    // Bouton 1 
    
    this.bt1.setBounds(0, 340, 75, 60);
    
    this.bt1.setBackground(Color.GRAY);
    
    this.bt1.setForeground(Color.WHITE);
    
    this.bt1.setFont(fButton);
    
    this.bt1.addActionListener(this);
    
    this.pan.add(bt1);
    
    // Bouton 2
    
    this.bt2.setBounds(75, 340, 75, 60);
    
    this.bt2.setBackground(Color.GRAY);
    
    this.bt2.setForeground(Color.WHITE);
    
    this.bt2.setFont(fButton);
    
    this.bt2.addActionListener(this);
    
    this.pan.add(bt2);
    
    // Bouton 3
    
    this.bt3.setBounds(145, 340, 75, 60);
    
    this.bt3.setBackground(Color.GRAY);
    
    this.bt3.setForeground(Color.WHITE);
    
    this.bt3.setFont(fButton);
    
    this.bt3.addActionListener(this);
    
    this.pan.add(bt3);
    
    // Bouton +
    
    this.bt10.setBounds(215, 340, 75, 60);
    
    this.bt10.setBackground(new Color(255, 140, 0));
    
    this.bt10.setForeground(Color.WHITE);
    
    this.bt10.setFont(fButton);
    
    this.bt10.addActionListener(this);
    
    this.pan.add(bt10);
    
    /* 5eme ligne : 0 = */
    
    // Bouton 0
    
    this.bt0.setBounds(0, 400, 150, 60);
    
    this.bt0.setBackground(Color.GRAY);
    
    this.bt0.setForeground(Color.WHITE);
    
    this.bt0.setFont(fButton);
    
    this.bt0.addActionListener(this);
    
    this.pan.add(bt0);
    
    // Bouton ,
    
    this.bt18.setBounds(145, 400, 75, 60);
    
    this.bt18.setBackground(Color.GRAY);
    
    this.bt18.setForeground(Color.WHITE);
    
    this.bt18.setFont(fButton);
    
    this.bt18.addActionListener(this);
    
    this.pan.add(bt18);
    
    // Bouton =
    
    this.bt11.setBounds(215, 400, 75, 60);
    
    this.bt11.setBackground(new Color(255, 140, 0));
    
    this.bt11.setForeground(Color.WHITE);
    
    this.bt11.setFont(fButton);
    
    this.bt11.addActionListener(this);
    
    this.pan.add(bt11);
    
    /* Affichage du contenus de la fenêtre */
    
    this.setContentPane(pan);
    
    /* Affichage de la fenêtre */
    
    this.setVisible(true);
    
    }
    
    public static void main(String[] args) {
    
    Calculatrice maCalculette = new Calculatrice();
    
    }
    
    public void actionPerformed(ActionEvent e) {
    
    //Bouton ,
    
    if (e.getSource() == this.bt18) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true && this.lab1.getText().contains(".") == false) {
    
    this.lab1.setText(this.lab1.getText() + ".");
    
    }
    
    if (this.lab2.getText().isEmpty() == false && this.lab3.getText().contains(".") == false) {
    
    this.lab3.setText(this.lab3.getText() + ".");
    
    }
    
    }
    
    // Bouton 0
    
    if (e.getSource() == this.bt0) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "0");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "0");
    
    }
    
    }
    
    // Bouton 1
    
    if (e.getSource() == this.bt1) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "1");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "1");
    
    }
    
    }
    
    // Bouton 2
    
    if (e.getSource() == this.bt2) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "2");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "2");
    
    }
    
    }
    
    // Bouton 3
    
    if (e.getSource() == this.bt3) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "3");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "3");
    
    }
    
    }
    
    // Bouton 4
    
    if (e.getSource() == this.bt4) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "4");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(lab3.getText() + "4");
    
    }
    
    }
    
    // Bouton 5
    
    if (e.getSource() == this.bt5) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "5");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "5");
    
    }
    
    }
    
    // Bouton 6
    
    if (e.getSource() == this.bt6) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "6");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "6");
    
    }
    
    }
    
    // Bouton 7
    
    if (e.getSource() == this.bt7) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "7");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "7");
    
    }
    
    }
    
    // Bouton 8
    
    if (e.getSource() == this.bt8) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "8");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "8");
    
    }
    
    }
    
    // Bouton 9
    
    if (e.getSource() == this.bt9) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "9");
    
    }
    
    if (this.lab2.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "9");
    
    }
    
    }
    
    // Bouton +
    
    if (e.getSource() == this.bt10) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    if (this.lab1.getText().isEmpty() == false) {
    
    this.lab2.setText("+");
    
    }
    
    if (this.lab4.getText().isEmpty() == false) {
    
    this.lab1.setText(this.lab4.getText());
    
    this.lab2.setText("+");
    
    this.lab4.setText("");
    
    }
    
    }
    
    // Bouton =
    
    //Operation +
    
    if (e.getSource() == this.bt11) {
    
    if (this.lab2.getText() == "+" && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.resultat = Double.parseDouble(this.lab1.getText()) + Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e1) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("+ ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "+" && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText());
    
    this.resultat = this.resultat + Double.parseDouble(this.lab1.getText());
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("+1 ?");
    
    } 
    
    }
    
    if (this.lab2.getText() == "+" && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText());
    
    this.resultat = this.resultat + Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("+2 ?");
    
    } 
    
    }
    
    if (this.lab2.getText() == "+" && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText());
    
    this.resultat = this.resultat + (Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText()));
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("+3 ?");
    
    } 
    
    }
    
    //Operation -
    
    if (this.lab2.getText() == "-" && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.resultat = Double.parseDouble(this.lab1.getText()) - Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e2) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("- ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "-" && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText());
    
    this.resultat = Double.parseDouble(this.lab1.getText()) - this.resultat;
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("-1 ?");
    
    } 
    
    }
    
    if (this.lab2.getText() == "-" && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText());
    
    this.resultat = this.resultat - Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("-2 ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "-" && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText());
    
    this.resultat = this.resultat - (Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText()));
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("-3 ?");
    
    }
    
    }
    
    //Operation X
    
    if (this.lab2.getText() == "X"  && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e3) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("X ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "X"  && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = (Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText())) * Double.parseDouble(this.lab1.getText());
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e3) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("X1 ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "X"  && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.resultat = (Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText())) * Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e3) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("X2 ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "X"  && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = (Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText())) * (Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText()));
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e3) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("X3 ?");
    
    }
    
    }
    
    //Operation ÷
    
    if (this.lab2.getText() == "÷"  && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.resultat = Double.parseDouble(this.lab1.getText()) / Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("÷ ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "÷"  && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText());
    
    this.resultat = Double.parseDouble(this.lab1.getText()) / this.resultat;
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("÷1 ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "÷"  && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²") == false) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText());
    
    this.resultat = this.resultat / Double.parseDouble(this.lab3.getText());
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("÷2 ?");
    
    }
    
    }
    
    if (this.lab2.getText() == "÷"  && this.lab1.getText().endsWith("²") && this.lab3.getText().endsWith("²")) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.lab3.setText(this.lab3.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText());
    
    this.resultat = this.resultat / (Double.parseDouble(this.lab3.getText()) * Double.parseDouble(this.lab3.getText()));
    
    this.lab4.setText("" + df.format(this.resultat));
    
    } catch (Exception e4) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("÷3 ?");
    
    }
    
    }
    
    //Operation x²
    
    if (this.lab1.getText().endsWith("²") && this.lab3.getText().isEmpty() == true) {
    
    try {
    
    this.lab1.setText(this.lab1.getText().replace("²", ""));
    
    this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab1.getText());
    
    this.lab4.setText(df.format(this.resultat));
    
    } catch (Exception e5) {
    
    this.lab5.setText("Erreur de syntaxe : ");
    
    this.lab6.setText("² ?");
    
    }
    
    }
    
    this.lab1.setText("");
    
    this.lab2.setText("");
    
    this.lab3.setText("");
    
    }
    
    // Bouton -
    
    if (e.getSource() == this.bt12) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    if (this.lab1.getText().isEmpty() == false) {
    
    this.lab2.setText("-");
    
    }
    
    if (this.lab4.getText().isEmpty() == false) {
    
    this.lab1.setText(this.lab4.getText());
    
    this.lab2.setText("-");
    
    this.lab4.setText("");
    
    }
    
    }
    
    // Bouton X
    
    if (e.getSource() == this.bt13) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    if (this.lab1.getText().isEmpty() == false) { 
    
    this.lab2.setText("X");
    
    }
    
    if (this.lab4.getText().isEmpty() == false) {
    
    this.lab1.setText(this.lab4.getText());
    
    this.lab2.setText("X");
    
    this.lab4.setText("");
    
    }
    
    }
    
    // Bouton ÷
    
    if (e.getSource() == this.bt17) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    if (this.lab1.getText().contains("=")) {
    
    this.lab1.setText(this.lab1.getText().substring(2));
    
    }
    
    if (this.lab1.getText().isEmpty() == false) {
    
    this.lab2.setText("÷");
    
    }
    
    if (this.lab4.getText().isEmpty() == false) {
    
    this.lab1.setText(this.lab4.getText());
    
    this.lab2.setText("÷");
    
    this.lab4.setText("");
    
    }
    
    }
    
    // Bouton x²
    
    if (e.getSource() == this.bt16) {
    
    if (this.lab3.getText().isEmpty() == true && this.lab4.getText().isEmpty() == true) {
    
    this.lab1.setText(this.lab1.getText() + "²");
    
    }
    
    if (this.lab3.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText() + "²");
    
    }
    
    if (this.lab4.getText().isEmpty() == false) {
    
    this.lab4.setText(this.lab4.getText() + "²");
    
    this.lab1.setText(this.lab4.getText());
    
    this.lab4.setText("");
    
    }
    
    }
    
    //Bouton %
    
    if (e.getSource() == this.bt15) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    this.lab4.setText("");
    
    if (this.lab2.getText().isEmpty() == true && this.lab1.getText().contains(".") == false && this.lab1.getText().length()>2) {
    
    this.lab1.setText(this.lab1.getText().substring(0, this.lab1.getText().length() - 2) 
    
    + "." + this.lab1.getText().substring(this.lab1.getText().length() - 2, this.lab1.getText().length()));
    
    }
    
    if (this.lab3.getText().isEmpty() == false && this.lab3.getText().contains(".") == false && this.lab3.getText().length()>2) {
    
    this.lab3.setText(this.lab3.getText().substring(0, this.lab3.getText().length() - 2) 
    
    + "." + this.lab3.getText().substring(this.lab3.getText().length() - 2, this.lab3.getText().length()));
    
    }
    
    if (this.lab2.getText().isEmpty() == true && this.lab1.getText().contains(".") == false && this.lab1.getText().length()==2) {
    
    this.lab1.setText("0." + this.lab1.getText());
    
    }
    
    if (this.lab3.getText().isEmpty() == false && this.lab3.getText().contains(".") == false && this.lab3.getText().length()==2) {
    
    this.lab3.setText("0." + this.lab3.getText());
    
    }
    
    if (this.lab2.getText().isEmpty() == true && this.lab1.getText().contains(".") == false && this.lab1.getText().length()==1) {
    
    this.lab1.setText("0.0" + this.lab1.getText());
    
    }
    
    if (this.lab3.getText().isEmpty() == false && this.lab3.getText().contains(".") == false && this.lab3.getText().length()==1) {
    
    this.lab3.setText("0.0" + this.lab3.getText());
    
    }
    
    }
    
    // Boutou AC (Supprimer)
    
    if (e.getSource() == this.bt14) {
    
    if (this.lab1.getText().isEmpty() == false && this.lab2.getText().isEmpty() == true) {
    
    this.lab1.setText("");
    
    }
    
    if (this.lab2.getText().isEmpty() == false && this.lab3.getText().isEmpty() == true) {
    
    this.lab2.setText(this.lab2.getText().substring(0, this.lab2.getText().length() - 1));
    
    }
    
    if (this.lab2.getText().isEmpty() == false && this.lab3.getText().isEmpty() == false) {
    
    this.lab3.setText(this.lab3.getText().substring(0, this.lab3.getText().length() - 1));
    
    }
    
    if (this.lab4.getText().isEmpty() == false) {
    
    this.lab4.setText("");
    
    }
    
    if (this.lab5.getText().isEmpty() == false || this.lab6.getText().isEmpty() == false) {
    
    this.lab5.setText("");
    
    this.lab6.setText("");
    
    }
    
    }
    
    }
    
    }


    PS : je ne sais pas pk ici entre les ligne 80 et 450 mon code parait grisé mais ça marche très bien normalement

    -
    Edité par nahkiniverson 11 février 2022 à 11:35:43

    • Partager sur Facebook
    • Partager sur Twitter
      11 février 2022 à 4:04:33

      Bonjour,

      Peux-tu éditer ton message précédent et remettre ton code avec le bouton </>, stp ? Sinon, c'est illisible.

      Deux premières remarques en attendant.

      Ton code contient beaucoup de répétitions. Pour éviter ces répétitions, tu peux créer des classes ou des méthodes, ce qui allègera ton code. Par exemple, une classe pour le code commun à tous tes boutons avec comme sous-classe, une classe pour les boutons des chiffres et une classe pour chaque bouton de fonction.

      Tu utilises des noms de variables qui ne veulent rien dire puis tu ajoutes des commentaires pour dire ce qu'elles représentent. C'est lourd et ça rend ton code difficile  à lire. Une meilleure pratique est de choisir des noms de variable qui ont du sens. Par exemple, au lieu de

      Button b10

      choisis plutôt

      Button boutonPlus
      // ou
      Button btnPlus




      • Partager sur Facebook
      • Partager sur Twitter
        11 février 2022 à 10:34:28

        Bonjour, Évitez les titres de sujets avec "problème" si vous postez on se doute que vous avez un problème, inutile de l'indiquer dans le titre cela n'apporte rien comme information quand au contenu du sujet.

        Le message qui suit est une réponse automatique activée par un membre de l'équipe. Les réponses automatiques leur permettent d'éviter d'avoir à répéter de nombreuses fois la même chose, ce qui leur fait gagner du temps et leur permet de s'occuper des sujets qui méritent plus d'attention.
        Nous sommes néanmoins ouverts et si vous avez une question ou une remarque, n'hésitez pas à contacter la personne en question par Message Privé.

        Pour plus d'informations, nous vous invitons à lire les règles générales du forum

        Merci de colorer votre code à l'aide du bouton Code

        Les forums d'Openclassrooms disposent d'une fonctionnalité permettant de colorer et mettre en forme les codes source afin de les rendre plus lisibles et faciles à manipuler par les intervenants. Pour cela, il faut utiliser le bouton Code de l'éditeur, choisir un des langages proposés et coller votre code dans la zone prévue. Si vous utilisez l'éditeur de messages en mode Markdown, il faut utiliser les balises <pre class="brush: java;">Votre code ici</pre>.

        Merci de modifier votre message d'origine en fonction.

        Liens conseillés

        -
        Edité par AbcAbc6 11 février 2022 à 10:39:15

        • Partager sur Facebook
        • Partager sur Twitter
          11 février 2022 à 11:17:20

          Au passage -vous n'y êtes évidemment pour rien- awt/swing est largement obsolète depuis un bon paquet d'années, remplacé par JavaFX / Java Fx 2.0 (2011).

          JavaFX est devenu LE truc officiel intégré avec Java 8 (2014), et en est ressorti un peu plus tard (Java 11, 2018) sous forme de module pour dissocier son développement de celui du JDK.

          Avec tout ça on est maintenant en 2022 avec Java 17. Et Java 18 sort le 22 mars.

          -
          Edité par michelbillaud 11 février 2022 à 11:20:24

          • Partager sur Facebook
          • Partager sur Twitter
            11 février 2022 à 11:25:56

            C'est modifier, effectivement c'est bcp plus clair lol

            Merci pour vos premières remarques tout d'abord. Pour en revenir à mon problème, je n'arrive pas à comprendre pk il m'est impossible d'effectuer plusieurs opérations à la suite étant donné les lignes suivantes entre les lignes 807 et 813 pour une addition après un premier calcul par exemple

             
            if (this.lab4.getText().isEmpty() == false) {
             
            this.lab1.setText(this.lab4.getText());
             
            this.lab2.setText("+");
             
            this.lab4.setText("");
             
            }

            J'arrive à court d'idées et je ne vois plus quoi modifier pour remédier à ça :/

            -
            Edité par nahkiniverson 11 février 2022 à 11:26:55

            • Partager sur Facebook
            • Partager sur Twitter
              11 février 2022 à 15:51:37

              > à court d'idée 

              Avant de vouloir modifier quoi que ce soit, commence par décrire précisément un scénario d'erreur

              Exemple 

              • Je clique sur 2 + 2 =
              • Ça affiche 5
              • Ça devrait être 4

              A partir de la, on peut voir ce qui se passe pendant l'exécution, et comparer avec ce qu'on croit que ça devrait faire. Et APRES on  pourra envisager de chercher ce qu'il faut changer dans le code.

              PS  Tes 10 boutons pour les chiffres ont un comportement similaire, qui peut être décrit par une méthode qui prend en parametre un entier de 0 à 9. En restructurant ton code tu t'y retrouveras mieux. Là ton code est beaucoup trop gros.

              ---

              PS: avec JavaFX (et le bon usage de tableau de paramètres), la mise en place de l'interface prend une petite centaine de lignes

              package fx1;
              
              import java.util.ArrayList;
              import javafx.application.Application;
              import javafx.stage.Stage;
              import javafx.scene.Scene;
              import javafx.scene.control.*;
              import javafx.scene.layout.*;
              
              public class Fx1 extends Application {
              
                  final int COL_WIDTH = 50, ROW_HEIGHT = 50;
              
                  record Zone(String label, int col, int row, int colSpan, int rowSpan) {
              
                      public Zone(String label, int col, int row) {
                          this(label, col, row, 1, 1);
                      }
                  }
                  
                  enum Action {
                      CLEAR, DIVIDE, MULTIPLY, ADD, SUBTRACT, TOTAL, COMMA
                  }
              
                  static final Zone[] buttonZones = {
                      new Zone("0", 0, 5, 2, 1),
                      new Zone("1", 2, 4),
                      new Zone("2", 1, 4),
                      new Zone("3", 0, 4),
                      new Zone("4", 2, 3),
                      new Zone("5", 1, 3),
                      new Zone("6", 0, 3),
                      new Zone("7", 2, 2),
                      new Zone("8", 1, 2),
                      new Zone("9", 0, 2),
                      new Zone("C", 0, 1),
                      new Zone("/", 1, 1),
                      new Zone("*", 2, 1),
                      new Zone("-", 3, 1),
                      new Zone("+", 3, 2, 1, 2),
                      new Zone("=", 3, 4, 1, 2),
                      new Zone(",", 2, 5)
                  };
              
                  static final Zone displayZone = new Zone("display", 0, 0, 4, 1);
              
                  public static void main(String[] args) {
                      launch();
                  }
              
                  Label display;
                  ArrayList<Button> buttons = new ArrayList<>();
              
                  @Override
                  public void start(Stage stage) throws Exception {
                      var grid = new GridPane();
                      display = new Label("...");
                      display.setPrefSize(COL_WIDTH * displayZone.colSpan(),
                              ROW_HEIGHT * displayZone.rowSpan());
                      grid.add(display, displayZone.col(), displayZone.row(), 
                              displayZone.colSpan(), displayZone.rowSpan());
                      for (var a : buttonZones) {
                          var button = new Button(a.label());
                          button.setPrefSize(COL_WIDTH * a.colSpan(), ROW_HEIGHT * a.rowSpan());
                          grid.add(button, a.col(), a.row(),
                                  a.colSpan(), a.rowSpan());
                          buttons.add(button);
                      }
                      Scene s = new Scene(grid, 600, 400);
                      stage.setScene(s);
                      
                      // MISE EN PLACE DES ACTIONS
                      
                      for (int i = 0; i <= 9; i++) {
                          final var digit = i;
                          buttons.get(i).setOnAction( (e) ->enterDigit(digit));
                      }
                      buttons.get(10).setOnAction((e) -> executeAction(Action.CLEAR));
                      buttons.get(11).setOnAction((e) -> executeAction(Action.DIVIDE));
                      buttons.get(12).setOnAction((e) -> executeAction(Action.MULTIPLY));
                  
                      buttons.get(13).setOnAction((e) -> executeAction(Action.SUBTRACT));
                      buttons.get(14).setOnAction((e) -> executeAction(Action.ADD));
                      buttons.get(15).setOnAction((e) -> executeAction(Action.TOTAL));
                      buttons.get(16).setOnAction((e) -> executeAction(Action.COMMA));
                      
                      stage.show();
                  }
                  
                  // cA SE PASSE ICI
                  void enterDigit(int n) {
                      System.out.format("digit %d\n", n);
                  }
                  
                  void executeAction(Action a) {
                      System.out.format("action %s\n", a);   
                  }
              }


              -
              Edité par michelbillaud 11 février 2022 à 18:29:46

              • Partager sur Facebook
              • Partager sur Twitter
                12 février 2022 à 19:14:53

                Comme scénario d'erreur, si je fais une première opération disons

                9²+5, ça va me donner 86

                puis si je continue et ajoute +4, ca me fait

                "Erreur de syntaxe : + ?", soit l'erreur du catch ci-dessous :

                // Bouton =
                		//Operation +
                		if (e.getSource() == this.bt11) {
                			if (this.lab2.getText() == "+" && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²") == false) {
                				try {
                					this.resultat = Double.parseDouble(this.lab1.getText()) + Double.parseDouble(this.lab3.getText());
                					this.lab4.setText(df.format(this.resultat));
                				} catch (Exception e1) {
                					this.lab5.setText("Erreur de syntaxe : ");
                					this.lab6.setText("+ ?");
                				}
                			}

                Evidemment pour les multiplications, soustractions et divisions ça ne sera pas les même erreurs, si lors de mon premier résultat 86 je le multiplie par exemple par 4 ça me donne l'erreur "X ?"

                //Operation X
                			if (this.lab2.getText() == "X"  && this.lab1.getText().endsWith("²") == false && this.lab3.getText().endsWith("²") == false) {
                				try {
                					this.resultat = Double.parseDouble(this.lab1.getText()) * Double.parseDouble(this.lab3.getText());
                					this.lab4.setText("" + df.format(this.resultat));
                				} catch (Exception e3) {
                					this.lab5.setText("Erreur de syntaxe : ");
                					this.lab6.setText("X ?");
                				}
                			}

                Aussi le carré n'a pas d'importance dans mon exemple.

                La première opération n'aura jamais de problèmes à s'effectuait mais la suivante affichera une erreur. La seule solution étant de cliquer sur le bouton AC

                Pour mes 10 boutons de chiffres effectivement je devrais rédiger une méthode ça serait plus clair. Par contre JavaFX on a pas encore vu donc je pense pas que je devrais l'utiliser pour mon projet, bien que ça a l'air vraiment pas mal vu le rendu visuel. 

                • Partager sur Facebook
                • Partager sur Twitter
                  13 février 2022 à 8:56:34

                  Le rendu visuel, on s'en fiche un peu, l'important c'est l'utilisation d'un GridLayout pour positionner facilement les boutons. Ça existe avec awt/swing.

                  Je ne recommande pas d'utiliser une techno quand le prof vous dit d'en employer une autre, ca va le fâcher, surtout si ça montre que sa connaissance de java remonte à la dynastie mérovingienne.

                  C'était quand même une occasion de montrer javafx (qui ressemble fortement au graphisme en javascript, c'est pas perdu), et les améliorations de java

                  • Les records qui remplacent les classes "stupides"
                  • Les "lambdas" qui évitent les classes anonymes
                  • Les callbacks dans les boutons

                  ---

                  Quand on tient une erreur, il faut l'examiner en détail.

                  Dans le try/catch, le type Exception est beaucoup trop general. Il est probable qu'il s'agisse d'une erreur de conversion (parse),  et faire afficher "erreur de syntaxe" induit en erreur.

                  Logiquement, si c'est pas le comportement attendu, on a besoin de savoir precisement qui a fait ca, et pourquoi. Utiliser un breakpoint et/ou un affichage sur console dans le catch pour examiner les données à ce moment là.

                  PS nommer les variables lab1, lab2, lab3, c'est un bon moyen de ne plus savoir à quoi elles servent, et se mélanger les pinceaux. Se créer son propre enfer.

                  -
                  Edité par michelbillaud 13 février 2022 à 9:14:13

                  • Partager sur Facebook
                  • Partager sur Twitter

                  Calculatrice

                  × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                  × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                  • Editeur
                  • Markdown