IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

avec Java Discussion :

Classes d une calculatrice


Sujet :

avec Java

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    22
    Détails du profil
    Informations personnelles :
    Localisation : Royaume-Uni

    Informations forums :
    Inscription : Décembre 2009
    Messages : 22
    Points : 26
    Points
    26
    Par défaut Classes d une calculatrice
    Bonjour
    me suis mise a java recemment, j ai suivi un tutorial ou etait demande de faire une calculatrice or tout etait contenu dans uen seule classe.
    J ai sougaite la coder en plusieurs classes.

    Mon soucis principal a ete que m emmmele pas mal les pates au niveau des relations entre les classes.
    je voulais au depart que calculator soit la classe qui gere les relations entre les autres mais.
    Mais au final elle instancie juste les Claases Calcul et Display, les communique aux objets bouttons et donc Listener à leur instanciation, Lobjet Listener leur prendra et renverra des informations.
    La classe display permet de renvoyer l input en double, la je ne suis pas sur que ce soit un role logique pour un objet d affichage.

    Donc voici mes classe. En attente de critique et conseils. Merci

    - Class calculator extends JFrame :
    instancie Calcul et Display
    La fenete principale et les panels subContainers
    Cree les objets boutton :numeros et operateurs
    Fonction main

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
     
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
     
     
    class Calculator extends JFrame {
     
    	// instances
    		private Display display;
    		private Calcul calcul;
     
    	// Containers
    		private JPanel mainContainer = new JPanel();
    		private JPanel screenContainer = new JPanel();
    		private JPanel numberContainer = new JPanel();
    		private JPanel operatorContainer = new JPanel();
     
    		private Button button;
     
     
    	/* Constructor
    	 * Instances of Displaya nd Calcul
    	 * Window configuration : size,title, close, location, rezise
    	 * initComponents, add to window
    	 */
     
    	public Calculator(){
    		calcul = new Calcul();
    		display = new Display();
     
    		//window settings
    		this.setSize(250,250);
    		this.setTitle("Calculator");
    		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		this.setLocationRelativeTo(null);
    		this.setResizable(false);
     
    		//add components to mainContainer
    		initComponents();
     
    		//add main container to the window
    		this.setContentPane(mainContainer);
     
    		this.setVisible(true);
     
    	}	
     
     
    	/* 	set subContainers properties
    	 *	init components and add to subContainers 
    	 *	add SubContainers to mainContainer	
    	 */
     
    	public void initComponents(){
     
    		//Sub Containers properties
    		screenContainer.setPreferredSize( new Dimension(225,25) );
    		screenContainer.setBorder(BorderFactory.createLineBorder( Color.BLACK ));
    		numberContainer.setPreferredSize( new Dimension(171,220) );
    		operatorContainer.setPreferredSize( new Dimension(57,220) );
     
    		//add components to subcontainers
    		screenContainer.add( display );	
    		initNumberContainer();
    		initOperatorContainer();
     
    		//add subcontainers to mainContainer
    		mainContainer.add( screenContainer, BorderLayout.NORTH );
    		mainContainer.add( numberContainer, BorderLayout.CENTER );
    		mainContainer.add( operatorContainer, BorderLayout.EAST);
     
    	}
     
     
    	/* Create new button for each number,., and egual
    	 * Add each bouton to the numberContainer
    	 */
     
    	public void initNumberContainer(){
    		String[] numberStringArray = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "="};
    		for( int i=0; i< numberStringArray.length; i++){
    			button = new Button( numberStringArray[i], "number", display, calcul);
    			numberContainer.add(button );		
    		}	
    	}
     
    	/* Create new button for each operator
    	 * Add each bouton to the operatorContainer
    	 */
     
    	public void initOperatorContainer(){
    		String[] operatorStringArray ={ "C", "+", "-" , "x" , "/" };
    		for( int i=0; i< operatorStringArray.length; i++){
    			button = new Button( operatorStringArray[i],"operator", display, calcul);
    			operatorContainer.add( button );
    		}
    	}
     
     
    	/* Main funtion : instance of calculator
    	 */
     
    	public  static  void    main(String args[]) {
     
            Calculator calculator = new Calculator();
        }
     
    }
    - Button extend JButton :
    necessite une instance de calcul et de display comme arguments pour ce construire

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    import javax.swing.JButton;
    import java.awt.Dimension;
     
    public class Button extends JButton {
     
    	private String type;
     
     
    	/* Set button properties : text, syze, type, dimension
    	 *	set listener
    	 */
    	public Button(String inputStr, String inputType, Display display, Calcul calcul){
     
    	 	this.type=inputType;
    	 	this.setText(inputStr);
    	 	this.addActionListener( new Listener( display, calcul ) )	;
    	 	assignSize();
    	}
     
    	/* Set dimension depending of button type
    	 */
    	public void assignSize(){
     
    		if( type.equals("number") ){
    	 		this.setPreferredSize( new Dimension(50,38) );
     
    	 	} else {
    	 		this.setPreferredSize(  new Dimension(50,29) );
    	 	}
     
    	}
     
     
    }
    - Listener implements ActionListener
    necessite une instance de calcul et de display comme arguments pour ce construire
    demande et renvoi des information aux objects display et calcul

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
     
    class Listener implements ActionListener  {
     
    	private Display display;
    	private Calcul calcul;
     
     
    	public Listener( Display display, Calcul calcul ){
    			this.display = display;
    			this.calcul = calcul;
     
    	}
     
    	/*  Assign action depending buttons 
    	 */
     
    	public void actionPerformed(ActionEvent e){
     
    			String stringInput = ((Button)e.getSource()).getText(); 	
     
               	if( '0' <= stringInput.charAt(0) && stringInput.charAt(0) <= '9' || stringInput.equals(".") ){
     
    	           		if( display.getUpdate() ){
    	           				display.setUpdate(false);
    	           		} else	if( ! display.getText().equals("0") ){
    	                    	stringInput = display.getText() + stringInput;
    	           		}
     
    					display.setText(stringInput);
     
      			} else if( stringInput.equals("C") ){
               		calcul.reset();
    				display.reset();
     
      			} else if( stringInput.equals("=") ){
     
    				calcul.doOperation( display.getInput() );
    				display.updateDisplay( calcul.getTotal() );
           			calcul.reset();	
     
               	} else {
     
               		calcul.doOperation( display.getInput() );
     
               		if( stringInput.equals("+") ){
               			calcul.setNextoperator(calcul.PLUS);
     
    	           	} else if( stringInput.equals("-") ){
    	 				calcul.setNextoperator(calcul.SUB);
     
    	           	} else if( stringInput.equals("x") ){
    	           		calcul.setNextoperator(calcul.MUL);
     
    	           	} else if (stringInput.equals("/") ){
    	           		calcul.setNextoperator(calcul.DIV);			
    	           	}
     				display.updateDisplay( calcul.getTotal() );
               	}
     
    	}
    }
    - Calcul : class ou se font les operations
    recoit les informations necessaires au calcul par les objets Listener

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    public class Calcul {
     
        public  static  final   int PLUS=1;
        public  static  final   int SUB=2;
        public  static  final   int MUL=3;
        public  static  final   int DIV=4;
     
    	private  double total = 0;
    	private  boolean start = true;
    	private int operator;
     
     
    	public void doOperation(double number){
    		if(start){
    			total = number;
    			start=false;
     
    		} else {
    			switch(operator){
    					case PLUS: 	total = total + number;
    								break;
    					case SUB:	total = total - number;
    								break;
    					case MUL:	total = total * number;
    								break;
    					case DIV:	try{
    									total =total / number;
    								 }catch(ArithmeticException e){
               							  reset();
           							}
           							break;
    			}
    		}
    	}
     
    	public void setNextoperator( int operator){
    		this.operator=operator;
    	}
     
     
    	public void reset(){
    		total =0;
    		start=true;
    	}
     
    	public double getTotal(){
    		return total;
    	}
     
     
    }
    - Display extend JLabel: pour l ecran
    recoit les informations a afficher par les Listeners

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    import javax.swing.JLabel;
    import java.awt.Dimension;
     
    public class Display extends JLabel{
     
    	private Dimension dim = new Dimension(200,17);
    	private boolean update = false;
     
     
    	public Display(){
    		this.setText("0");
    		this.setHorizontalAlignment( this.RIGHT);
    		this.setPreferredSize( dim );
    	}
     
    	public void reset(){
    		this.setText("0");
    		update =false;
    	}
     
    	public boolean getUpdate(){
    		return update;
    	}
     
    	public void setUpdate(boolean value){
    		update = value;
    	}
     
    	public void updateDisplay(double number){
    		this.update=true;	
    		this.setText( String.valueOf( number ) );
    	}
     
    	public double  getInput(){
    		return Double.valueOf( getText() ).doubleValue();
    	}
     
    }

  2. #2
    Membre émérite
    Avatar de polymorphisme
    Homme Profil pro
    Publishing
    Inscrit en
    Octobre 2009
    Messages
    1 460
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Publishing
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2009
    Messages : 1 460
    Points : 2 371
    Points
    2 371
    Par défaut Un petit conseil
    Bonjour,

    pour faire des calculs, je te conseil très fortement d'utiliser la classe BigDecimal, car avec les doubles tu va être rapidement dépasser.

    http://java.sun.com/j2se/1.4.2/docs/...igDecimal.html
    Article : Installation de Cocoon
    Je ne réponds pas aux MP à caractère technique.

Discussions similaires

  1. modeliser une calculatrice MVC en UML (diagramme de classe)
    Par samira.kdc dans le forum Diagrammes de Classes
    Réponses: 1
    Dernier message: 17/10/2014, 17h19
  2. [Reflection] Classes implémentant une interface
    Par thibaut dans le forum API standards et tierces
    Réponses: 17
    Dernier message: 29/07/2004, 14h57
  3. classe dans une classe ?
    Par tut dans le forum UML
    Réponses: 23
    Dernier message: 25/06/2004, 15h00
  4. Réponses: 4
    Dernier message: 17/03/2004, 17h24
  5. [tomcat]chargement dynamique de classes depuis une webapp
    Par alphamax dans le forum Tomcat et TomEE
    Réponses: 2
    Dernier message: 12/03/2004, 09h59

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo