⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calculator.java

📁 java实现简易计算器
💻 JAVA
字号:
/**
 * @author zhangxiaoqing
 * @ID = 10031060
 */

import javax.swing.*;
import java.awt.*;       // needed for Container
import java.awt.event.*;  // needed for event types (listeners)


class Calculator extends JFrame implements ActionListener 
{

	JTextField jt;
  
    private double data1 ;       //the first operand
    private double data2 ;       //the second operand
    private double result ;      //the result
    private String oper ;     //the operator
    private String getRes ;   //store the operator "="
    private int operPreFlag = 0;//define a sign while enter the second 
    private int clearFlag = 0;
     double temp;                         //operand clear the operator
  
    public static void main(String [] args) 
    {
  	   
	  Calculator cal = new Calculator();
    }


    // Constructor sets up the window and gets things rolling.
    Calculator() 
    {
		Container c = getContentPane();
		// set up layout manager
		c.setLayout(new BorderLayout(10,10));
	
		// add single text Area
		jt = new JTextField();
		jt.setSize(100,40);
		jt.setFont(new Font("Arial",Font.BOLD,20));
		jt.setBackground(Color.WHITE);
		jt.setForeground(Color.BLUE);
		c.add(jt,BorderLayout.NORTH);

		// add a button panel 
		c.add( createButtonPanel(), BorderLayout.CENTER );
	

		// establish what happens when the window is closed
		// (without this the program would keep running!)
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//set the title
		setTitle("zhangxiaoqing_10031060");
		// set the size
		setSize(400,400);
		// turn it on
		setVisible(true);
    }


    JPanel createButtonPanel() 
    {
		// create a JPanel with a bunch of buttons in it arranged in
		// a grid.
		JPanel jp = new JPanel();

		// establish the layout manager
		// 4 rows, 4 cols everything 5 pixels apart
		jp.setLayout( new GridLayout(4,4,5,5));
	
		//store the operators in a array
		int OpeNum = 0;   // number of the operator
		String Operator[] = {"+","-","*","CLR","=","/"};

		// add a bunch of buttons
		
		JButton operButton = new JButton();
		int buttNum = 0;
		for (buttNum=0;buttNum<16&&OpeNum<6;buttNum++) 
		{		
			//setting "+","-","*" operator buttons
			if((buttNum+1)%4 == 0)
			{
				 operButton = new JButton(Operator[OpeNum++]);
			}
			else if(buttNum<3)
			{//setting 7,8,9 buttons
				 operButton = new JButton(new Integer(buttNum+7).toString());
			}
			//setting 4,5,6 buttons
			else if(buttNum==4 || buttNum==5 || buttNum==6)
			{
				 operButton = new JButton(new Integer(buttNum).toString());
			}
	  	    else if(buttNum<11)
	  	    {//setting 1,2,3 buttons
	  		   	 operButton = new JButton(new Integer(buttNum-7).toString());
	  		}
	  		else if(buttNum==12)
	  		{	//setting 0 button
	  			operButton = new JButton(new Integer(0).toString());
	  		}
            else if(buttNum == 13)
            {   //setting CLR button
                operButton = new JButton(Operator[OpeNum++]);
                operButton.setActionCommand("");
            }
            else
            {//setting "CLR","=","/" operator buttons
              	operButton = new JButton(Operator[OpeNum++]);
            }
            
	  		// change the font
	  	    operButton.setFont(new Font("宋体",Font.BOLD,30));

	  		// change the colors
	  		operButton.setBackground(Color.green);
	  		operButton.setForeground(Color.red);

	  		// set up the listener for this button
	  		// NOTE: We listen to ourself (we are an ActionListener!).
	  		operButton.addActionListener(this);
     
	  		// add the button to the panel 		
	  		jp.add(operButton);
	    }
	    return(jp);
    }


    // here is the method required as an ActionListener
    // (there is only one!)
    public void actionPerformed(ActionEvent e) 
    { 
  		String act = e.getActionCommand();
  		try
  		{
	   		//when press CLR button, it will clear all the variables
	   		if(act.equals(""))
	   		{
	   			jt.setText("");
	   			data1 = 0;
	   			data2 = 0;
	   			result = 0;
	   			oper = null;
	   			getRes = null;
	   		}
	   	
	   		//when press = button, display the result
	   		else if(act.equals("="))
	   		{
	   		    getRes = act;
				data2 = Double.parseDouble(jt.getText()); //store the second operand   

	   				jt.setText("");   //clear the text_box
	   		    if(oper.equals("/")&&data2 ==0 )
    		    { 
    			    
      	       	    jt.setText("Error! Divisor can not be 0!!!");
    		    }
       		    else
       		    {
       			 	result = this.calculation(data1,data2,oper);
       		    	jt.setText(Double.toString(result));
       		 	}
	   		}
	   	
	   		//when press operand buttons, calculate the data
	   		else if(act.equals("+")||act.equals("-")||act.equals("*")||act.equals("/"))
	   		{
	   			if(oper == null)
	   			{  //the data is the first one
	    			data1 = Double.parseDouble(jt.getText());
	    			oper = act;   //store the operator in the oper
	    			operPreFlag = 1; 
	    			jt.setText("");   //clear the text_box  	   				
	   			}
	   			else   //there is some data and operator
	   			{ 
	   		    	if(operPreFlag == 1)    //the previous one is a operator
	   		    	{   
	   		    		jt.setText(""); 
            		    jt.setText("Error! Input more operand!!! ");	
	   		    	}
	   		    	else                   //the input is right
	   		    	{
	   		    	    data2 = Double.parseDouble(jt.getText()); //store the second operand	
	   		    	   
	   		    	    if(oper.equals("/")&&data2 ==0 )
    		            { 
    			            jt.setText("");System.out.println("Error!Divisor can not be 0 ");
      	       	            jt.setText("Error! Divisor can not be 0!!!");
    					}
    					else
    					{
	   		    			data1 = this.calculation(data1,data2,oper);
	   		    			//jt.setText(""+data1);
       		            	jt.setText(Double.toString(data1));
       		            	clearFlag = 0;
       		            }
       		            oper = act;
	   		    	}
	   			}
	        }
	        else   //press the digital button
	        {
	        	if(operPreFlag == 1 || clearFlag == 0)
	        	{
	        	   jt.setText("");   //clear the text_box 	
	        	}
	        	operPreFlag = 0;
	        	clearFlag = 1;
	        }
	        
	        if(act != "=") //not display the "=" 
	        {
	          jt.setText(jt.getText() + act );
	        }
	   		System.out.println("data1 :"+data1);
	   		System.out.println("oper :"+oper);	   
	   		System.out.println("data2 :" +data2);
	   		System.out.println("result :" +result);
	   }
       catch(Exception e1)
       {
        	jt.setText("");
        	jt.setText("Error!!!");
       }
   }
	     

  
  //define addition
  public double add(double d1, double d2)
  {
  	return d1 + d2;
  }
  
  //define subtraction
  public double sub(double d1, double d2)
  {
  	return d1 - d2;
  }
  
  //define multiplication
  public double mul(double d1, double d2)
  {
  	return d1 * d2;
  }
  
  //define division
  public double div(double d1, double d2)
  {
  	return d1/d2;
  }
  
  //define calculations here
  public double calculation(double d1, double d2, String op) throws Exception
  {
  	try
  	{
  		if(op.equals("+"))
  		{
  			temp = this.add(d1,d2);
  		}
  		else if(op.equals("-"))
  		{
  			temp = this.sub(d1,d2);
  		}
  		else if(op.equals("*"))
  		{
  			temp = this.mul(d1,d2);
  		}
  		else if(op.equals("/"))
    	{
    		temp = this.div(d1,d2);
    	}
    	

    }
    catch(Exception e)
    {
    	jt.setText("");
    	jt.setText("Error!!!");
    }
        	return temp;
  }
  
  
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -