Java计算器的源代码

Java简单计算器源代码解析
本文分享了一段基础且实用的Java计算器源代码,适用于初学者参考学习。
import java.util.*; 
public class Calc { 
public static void main(String[] args) { 
Scanner input = new Scanner(System.in); 
System.out.println("*****************简单计算器****************"); 
System.out.println("*\t\t\t\t\t*"); 
System.out.println("* 使用说明: 1.加法  2.减法  3.乘法  4.除法   * 5.退出"); 
System.out.println("*\t\t\t\t\t*"); 
System.out.println("*****************************************"); 
 
for(int i=0;i<100;i++){ 
System.out.print("\n请选择运算规则:"); 
int num = input.nextInt();
if (num == 5) {
    break;
}
switch(num){ 
case 1: 
System.out.println("\n******你选择了加法******\n"); 
System.out.print("请输入第1个加数:"); 
int jiashu1 = input.nextInt(); 
System.out.print("请输入第2个加数:"); 
int jiashu2 = input.nextInt(); 
System.out.println("运算结果为:" + jiashu1 + " + " + jiashu1 + " = " + (jiashu1 + jiashu2)); 
break; 
case 2: 
System.out.println("\n******你选择了减法******\n"); 
System.out.print("请输入被减数:"); 
int jianshu1 = input.nextInt(); 
System.out.print("请输入减数:"); 
int jianshu2 = input.nextInt(); 
System.out.println("运算结果为:" + jianshu1 + " - " + jianshu2 + " = " + (jianshu1 - jianshu2)); 
break; 
case 3: 
System.out.println("\n******你选择了乘法******\n"); 
System.out.print("请输入第1个因数:"); 
int chengfa1 = input.nextInt(); 
System.out.print("请输入第2个因数:"); 
int chengfa2 = input.nextInt(); 
System.out.println("运算结果为:" + chengfa1 + " * " + chengfa2 + " = " + (chengfa1 * chengfa2)); 
break; 
case 4: 
System.out.println("\n******你选择了除法******\n"); 
System.out.print("请输入被除数:"); 
double chufa1 = input.nextInt(); 
System.out.print("请输入除数:"); 
double chufa2 = input.nextInt(); 
System.out.println("运算结果为:" + chufa1 + " / " + chufa2 + " = " + (chufa1 / chufa2) + " 余 " + (chufa1 % chufa2)); 
break; 
default: 
System.out.println("\n你的选择有错,请重新选择!"); 
break; 
}
} 
} 
}

这是一个很原始而且简单的计算器源代码



import java.awt.*;
import javax.swing.*;

import java.awt.event.*;

import javax.swing.border.*;

public class Calculator1 extends JFrame implements ActionListener
{
private JFrame jf;
 private JButton[] allButtons;
 private JButton clearButton;
 private JButton sinButton;
 private JButton cosButton;
 private JButton tanButton;
// private JButton cotButton;
 private JTextField jtf;
 private boolean isNew = true;
 private String recentOperation = null;
 private String recentNum = null;
 public Calculator1() 
 {
  
 /**
  * 设置窗口点击关闭按钮能关闭
  */
  jf=new JFrame("计算器1.0:JAVA");
  jf.addWindowListener(new WindowAdapter()
  {
   public void windowClosing(){
    System.exit(0);
   }
  }); 
  // 实例化所有的按钮以及编辑栏
  allButtons  = new JButton[16];
  clearButton = new JButton("DEL");
  sinButton   = new JButton("sin");
  cosButton   = new JButton("cos");
  tanButton   = new JButton("tan");
  jtf=new JTextField(25);
  jtf.setEditable(false);
//  jtf.setHorizontalAlignment(alignment)
  //给CanterPanel中的按钮添加标识符
  String str="123+456-789*0.=/";
  for(int i=0;i<allButtons.length;i++)
  {
   allButtons[i]=new JButton(str.substring(i,i+1));
 }
 }
 public void init(){
  //设置布局
  jf.setLayout(new BorderLayout());
  JPanel northPanel=new JPanel();
  JPanel centerPanel=new JPanel();
  JPanel southPanel=new JPanel();
  northPanel.setLayout(new FlowLayout());
  centerPanel.setLayout(new GridLayout(4,4));
  southPanel.setLayout(new GridLayout(1,4));
  
  northPanel.add(jtf);
  for(int i=0;i<16;i++){
   centerPanel.add(allButtons[i]);
  }
  southPanel.add(sinButton);
  southPanel.add(cosButton);
  southPanel.add(tanButton);
  //southPanel.add(cotButton);
  southPanel.add(clearButton);
  
  
  jf.add(northPanel,BorderLayout.NORTH);
  jf.add(centerPanel,BorderLayout.CENTER);
  jf.add(southPanel,BorderLayout.SOUTH);
  addEventHandler();
 }
 //添加事件监听
public void addEventHandler()
{
 jtf.addActionListener(this);
 for(int i=0;i<allButtons.length;i++)
 {
  allButtons[i].addActionListener(this);
 }
 /**
  * 给DEL注册
  */
  clearButton.addActionListener(new ActionListener()
  {
   public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
Calculator1.this.jtf.setText("");
}
   });
  
  /***
   * 实现sin,cos,tan 以及 allButton事件驱动按钮
   */
  sinButton.addActionListener(new ActionListener()
  {
  public void actionPerformed(ActionEvent e)
  {
  
double temp = Math.sin(Double.parseDouble(jtf.getText()));
  jtf.setText(String.valueOf(temp));
  return;
  }
  });
  cosButton.addActionListener(new ActionListener()
  {
  public void actionPerformed(ActionEvent e)
  {
  
double temp = Math.cos(Double.parseDouble(jtf.getText()));
  jtf.setText(String.valueOf(temp));
  return;
  }
  });
  tanButton.addActionListener(new ActionListener()
  {
  public void actionPerformed(ActionEvent e)
  {
  
double temp = Math.tan(Double.parseDouble(jtf.getText()));
  jtf.setText(String.valueOf(temp));
  return;
  }
  });
  /*cotButton.addActionListener(new ActionListener()
  {
  public void actionPerformed(ActionEvent e)
  {
  
double temp =- Double.parseDouble(jtf.getText());
  jtf.setText(String.valueOf(temp));
  return;
  }
  });*/
 }
 //对输入数字的事件处理
public void actionPerformed(ActionEvent e) 
  {
  String s= e.getActionCommand();
  if(s.charAt(0)>='0'&&s.charAt(0)<='9')
  {
  if(!isNew)
  jtf.setText(jtf.getText()+s);
  else
  jtf.setText(s);
  isNew = false;
  
  }
  /**
   * 对“.”的事件处理
   */
  else if (s.equals("."))
  {
  if(jtf.getText().indexOf(".")!=-1)
  return;
  if(!isNew &&jtf.getText()!="")
  jtf.setText(jtf.getText()+".");
  else
  jtf.setText("0.");
  isNew = false;
  
  }
  //对"="的事件处理
  else if(s.equals("="))
  {
 equalaction(e); 
  
  }
  else
  {
 if((jtf.getText()).equals(""))
 return;
 if(recentOperation !=null)equalaction(e);
  recentOperation = s;
  recentNum = jtf.getText();
  isNew = true;
  
  }
}
/**
 * 对运算符及计算过程的事件处理
 * @param e
 */
private void equalaction(ActionEvent e) {
// TODO Auto-generated method stub
if(recentOperation == null|| recentNum==null|| 
jtf.getText().equals(""))
return;
double last = 0,now = 0;

try
{
last = Double.parseDouble(recentNum);
now = Double.parseDouble(jtf.getText());
}
catch(NumberFormatException en)

{
recentOperation = null;
recentNum = null;
jtf.setText("数据输入不合法");
System.out.println("数据输入不合法");
isNew = true;
return;

}
if(recentOperation.equals("+"))
{
last+=now;

}
if(recentOperation.equals("-"))
{
last-=now;

}
if(recentOperation.equals("*"))
{
last*=now;

}
if(recentOperation.equals("/"))
{
last/=now;

}
jtf.setText(""+last);
recentNum = jtf.getText();
recentOperation=null;
isNew = true;
  }   
  
  
//对CenterPanel设置

public void setFontAndColor(){
  Font f=new Font("宋体",Font.BOLD,24);
  jtf.setFont(f);
  jtf.setBackground(new Color(0x8f,0xa0,0xfb));
  for(int i=0;i<16;i++)
  {
   allButtons[i].setFont(f);
   allButtons[i].setForeground(Color.RED);
  }
 }
 
 
 public void showMe(){
  init();
  setFontAndColor();
  jf.pack();
  jf.setVisible(true);
  jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 public static void main(String[] args){
  new Calculator1().showMe();
 }
}


可以用来参考

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * @version 
 * @author 
 */
public class Calculator
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(new Runnable()
         {
            public void run()
            {
               CalculatorFrame frame = new CalculatorFrame();
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               frame.setVisible(true);
            }
         });
   }
}

/**
 * A frame with a calculator panel.
 */
class CalculatorFrame extends JFrame
{
   public CalculatorFrame()
   {
      setTitle("Calculator");
      CalculatorPanel panel = new CalculatorPanel();
      add(panel);
      pack();
   }
}

/**
 * A panel with calculator buttons and a result display.
 */
class CalculatorPanel extends JPanel
{
   public CalculatorPanel()
   {
      setLayout(new BorderLayout());

      result = 0;
      lastCommand = "=";
      start = true;

      // add the display

      display = new JButton("0");
      display.setEnabled(false);
      add(display, BorderLayout.NORTH);

      ActionListener insert = new InsertAction();
      ActionListener command = new CommandAction();

      // add the buttons in a 4 x 4 grid

      panel = new JPanel();
      panel.setLayout(new GridLayout(4, 4));

      addButton("7", insert);
      addButton("8", insert);
      addButton("9", insert);
      addButton("/", command);

      addButton("4", insert);
      addButton("5", insert);
      addButton("6", insert);
      addButton("*", command);

      addButton("1", insert);
      addButton("2", insert);
      addButton("3", insert);
      addButton("-", command);

      addButton("0", insert);
      addButton(".", insert);
      addButton("=", command);
      addButton("+", command);

      add(panel, BorderLayout.CENTER);
   }

   /**
    * Adds a button to the center panel.
    * @param label the button label
    * @param listener the button listener
    */
   private void addButton(String label, ActionListener listener)
   {
      JButton button = new JButton(label);
      button.addActionListener(listener);
      panel.add(button);
   }

   /**
    * This action inserts the button action string to the end of the display text.
    */
   private class InsertAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String input = event.getActionCommand();
         if (start)
         {
            display.setText("");
            start = false;
         }
         display.setText(display.getText() + input);
      }
   }

   /**
    * This action executes the command that the button action string denotes.
    */
   private class CommandAction implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String command = event.getActionCommand();

         if (start)
         {
            if (command.equals("-"))
            {
               display.setText(command);
               start = false;
            }
            else lastCommand = command;
         }
         else
         {
            calculate(Double.parseDouble(display.getText()));
            lastCommand = command;
            start = true;
         }
      }
   }

   /**
    * Carries out the pending calculation.
    * @param x the value to be accumulated with the prior result.
    */
   public void calculate(double x)
   {
      if (lastCommand.equals("+")) result += x;
      else if (lastCommand.equals("-")) result -= x;
      else if (lastCommand.equals("*")) result *= x;
      else if (lastCommand.equals("/")) result /= x;
      else if (lastCommand.equals("=")) result = x;
      display.setText("" + result);
   }

   private JButton display;
   private JPanel panel;
   private double result;
   private String lastCommand;
   private boolean start;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值