Java实现计算器——升级记录中19.5.14……

这是入门java以来的第一个小项目,希望可以从中学到东西,而不是单纯地懂得Swing的一些功能,持续更新中

/*************************************************************************/

19.5.14 

//第一个类:主类
package Calculator_advance;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
public class Calculator_advance {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new WindowFlow("计算器");
	}
}




//第二个类:布局
package Calculator_advance;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;

public class WindowFlow extends JFrame implements ActionListener{
		JMenuBar menubar;
		JMenu menu;
		JMenuItem item1,item2,item3;
		JLabel inputScreen = new JLabel();
		int count=0;
		String str;
		static int choose=0;
		
		WindowFlow(String s)
		{
			setTitle(s);			
			setBounds(100,100,300,450);
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			//第一种:菜单选择
			menubar = new JMenuBar();
			menu = new JMenu("模式选择");
			item1 = new JMenuItem("基本型");
			item2 = new JMenuItem("科学型");
			item3 = new JMenuItem("关闭");
			menu.add(item1);
			menu.add(item2);
			menu.add(item3);
			menubar.add(menu);
			setJMenuBar(menubar);
		

			
			inputScreen.setSize(280,100);
			add(inputScreen,BorderLayout.NORTH);
			inputScreen.setText("0");
			inputScreen.setFont(new Font("SERIF",Font.BOLD,40));
			inputScreen.setHorizontalAlignment(JLabel.RIGHT);
			inputScreen.setBorder(BorderFactory.createLineBorder(Color.black));
			JPanel ButtonContainer = new JPanel();
			add(ButtonContainer);
			
			String Buttonnumbers[] = {"7","8","9","+", 
					                  "4","5","6","-", 
					                  "1","2","3","*", 
					                  "0",".","/","=",
					                  "clear"};
			for(String string:Buttonnumbers)
			{
				JButton b = new JButton(string);
				if(string !="clear")
				  b.setPreferredSize(new Dimension(60,60));
				else  b.setPreferredSize(new Dimension(240,60));
				ButtonContainer.add(b);
				b.addActionListener(this);
			}
			setVisible(true);	
			validate();
			
			/*
			 * 事件处理
			 */
			item1.addActionListener(new ActionListener() {
				   public void actionPerformed(ActionEvent e) 
				   {				
					  choose=1;
					  System.out.println(choose);
				   }
			   });
			item2.addActionListener(new ActionListener() {
				   public void actionPerformed(ActionEvent e) 
				   {				
					  choose=2;
					  System.out.println(choose);
				   }
			   });
			item3.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) 
				{
					System.exit(0);
				}
			});						
	}

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			MathSampleOperation Math =new MathSampleOperation();
			
			count++;
			if(count==1)
			  inputScreen.setText("");//不显示0
			
			if(e.getActionCommand()!="=")
			  inputScreen.setText(inputScreen.getText()+e.getActionCommand());
			else 
			{
				inputScreen.setText(inputScreen.getText()+"="+Math.eval(inputScreen.getText()));
			}
			if(e.getActionCommand().equals("clear")==true)
			{
				inputScreen.setText("0");
				count=0;
			}
			
		}	
}


//第三个类:算术操作
package Calculator_advance;

public class MathSampleOperation {

	public String str;
	public double numa,numb;
	public double eval(String str)//此处划分可以再优化
	{
		
	    String[] strnum = str.split("[\\p{Punct}]+");//\n 6\n9
	    String[] strstr = str.split("[\\d]+");// \n +
	    numa = Double.parseDouble(strnum[0]);
	    numb = Double.parseDouble(strnum[1]);    
	   switch (strstr[1]) {
	case "+":
		return numa+numb;
	case "-":
		return numa-numb;
	case "*":
		return numa*numb;
	case "/":
		return numa/numb;
	default:
		return Math.E;
	 }		 
   }
}



效果如图: 

Java实现计算器——升级记录中19.5.14……_第1张图片

上面主要实现的仅仅是基本型的整体布局和简单的两个数之间的运算!

接下来就需要不断完善功能啦,我会分时间段来完善,希望最后呈现给大家的是一个功能齐全的计算器! 

 

/*************************************************************************/

 

19.5.15——>主要实现了基本型的混合运算,只改了混合型运算的代码

//仅改动了第三个类——算术操作类(但这个方法比较麻烦,而且实现过程中自己忽略了一些知识点,导致找了很久)

//String类型的比较一定要用str.equals();不能用'=='

我开始习惯性地用了'==',之后过程测试中发现出现并没有进入条件语句中

package Calculator_advance;

import java.util.Scanner;

public class MathSampleOperation {

	public String str;
	
	public double eval(String str)//此处划分可以再优化
	{
		int i,k=0,count=0;
		double sum=0;
		double[] number = new double[20];
		String[] strArray =new String[20];
		
		double[] newnumber = new double[20];
		String[] newstrArray =new String[20];
		
	    String[] strnum = str.split("[\\p{Punct}]+");
	    String[] strstr = str.split("[\\d]+");
	    //输出部分为过程测试
	    for(i=0;i

思想是什么呢?

1 .首先不考虑括号存在的情况, 对数值和操作符划分好以后,先处理乘除运算;

2 .当遇到加减运算符时,将运算后的结果和存入一个新的数值数组中,加减运算符也存入一个新的运算符数组中;

3. 处理加减运算符,只要一遍循环就可处理了

思考这个过程:大体上乘除和加减就只有两种分布,*/+即乘除连续,*+/即乘除间断

,但需要很多判断,容易出错,而且这个算法的时间复杂度应该是O(n)吧!

效果图:Java实现计算器——升级记录中19.5.14……_第2张图片

上面主要实现的多个数之间的运算

接下来会接着实现基本型和科学性之间的页面切换,继续努力啦!

 

 

/*************************************************************************/

19.5.16——>只对基本型代码混合运算部分进行了整理,让人看的更清晰些;

package Calculator_advance;

import java.util.Scanner;

public class MathSampleOperation {

	public String str;
	
	public double eval(String str)//此处划分可以再优化
	{
		int i;
		int k=0;       //新操作符数组的操作符个数
		int count=0;   //次数标记
		double sum=0;  //乘除过程中的和
		double[] number = new double[20];
		String[] strArray =new String[20];
		
		double[] newnumber = new double[20];  //新数值数组
		String[] newstrArray =new String[20]; //新操作符数组-只含有 + -
		
	    String[] strnum = str.split("[\\p{Punct}]+");
	    String[] strstr = str.split("[\\d]+");
	    
	    /**********输出部分均为分步过程测试***********/
	    
	    for(i=0;i

 

/*************************************************************************/

19.5.19——>对欢迎界面和科学型的界面进行了完善,整体代码改动较大;以下是最新版本下的所有.java项目

//main函数
package Calculator_advance;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
public class Calculator_advance {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Windows("计算器");
	}
}




//欢迎界面面板
package Calculator_advance;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Windows extends JFrame{
	JMenuBar menubar;
	JMenu menu;
	JMenuItem item1,item2,item3;
	static int choose=0;
	
	//添加个人信息面盘
	JPanel Information = new JPanel();
	JLabel User =new JLabel("徐铭骏");
	JLabel ID =new JLabel("1170230039");
	
//	JTextArea 允许多行编辑
	JTextArea HelloText = new JTextArea(
			  "Hello, welcome to use!                                 "
			  +"Choose the left upper corner",100,100);
	
	public Windows(String string) {
		// TODO Auto-generated constructor stub
		
		setTitle(string);
		setBounds(100,100,300,450);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//第一种:菜单选择
		menubar = new JMenuBar();
		menu = new JMenu("模式选择");
		item1 = new JMenuItem("基本型",new ImageIcon("open.PNG"));
		item2 = new JMenuItem("科学型",new ImageIcon("open.PNG"));
		item3 = new JMenuItem("退出",new ImageIcon("close.PNG"));
		menu.add(item1);
		menu.add(item2);
		menu.add(item3);
		menubar.add(menu);
		setJMenuBar(menubar);
		
		//欢迎面盘
		HelloText.setFont(new Font("SERIF",Font.BOLD,30));
		HelloText.setLineWrap(true);	//设置多行文本框自动换行
		add(HelloText);
		
		//个人信息
		add(Information,BorderLayout.SOUTH);
		String ButtonInformation[] = {"User:徐铭骏","ID:1170230039"};
		for(String string1:ButtonInformation)
		{
			JButton b = new JButton(string1);
			b.setPreferredSize(new Dimension(120,60));
			Information.add(b);
		}

			
		/*
		 * 菜单栏事件处理
		 */
		item1.addActionListener(new ActionListener() {
			   public void actionPerformed(ActionEvent e) 
			   {				
				   Panel1 panel1 = new Panel1("基本型");
			   }
		   });
		item2.addActionListener(new ActionListener() {
			   public void actionPerformed(ActionEvent e) 
			   {		
				   Panel2 panel2 = new Panel2("科学型");
			   }
		   });
		item3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) 
			{
				System.exit(0);
			}
		});				
		setVisible(true);	
		validate();
	}

}




//基本型界面面板
package Calculator_advance;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;

public class Panel1 extends JFrame implements ActionListener{
		
		JLabel inputScreen = new JLabel();
		int count=0;
		String str;
		Windows window1 = new Windows("计算器");
		Panel1(String s)
		{
			setTitle(s);			
			setBounds(100,100,300,450);
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	

			
			inputScreen.setSize(280,100);
			add(inputScreen,BorderLayout.NORTH);
			inputScreen.setText("0");
			inputScreen.setFont(new Font("SERIF",Font.BOLD,40));
			inputScreen.setHorizontalAlignment(JLabel.RIGHT);
			inputScreen.setBorder(BorderFactory.createLineBorder(Color.black));
			JPanel ButtonContainer = new JPanel();
			add(ButtonContainer);
			
			String Buttonnumbers[] = {"7","8","9","+", 
					                  "4","5","6","-", 
					                  "1","2","3","*", 
					                  "0",".","/","=",
					                  "clear","reset"};
			for(String string:Buttonnumbers)
			{
				JButton b = new JButton(string);
				if(string !="clear" && string !="reset")
				  b.setPreferredSize(new Dimension(60,60));
				else  b.setPreferredSize(new Dimension(120,60));
				ButtonContainer.add(b);
				b.addActionListener(this);
			}
			setVisible(true);	
			validate();		
	}

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			MathSampleOperation MathSam =new MathSampleOperation();
			
			count++;
			if(count==1)
			  inputScreen.setText("");//不显示0
			
			if(e.getActionCommand()!="=")
			  inputScreen.setText(inputScreen.getText()+e.getActionCommand());
			else 
			{
				inputScreen.setText(inputScreen.getText()+"=");
				inputScreen.setText(inputScreen.getText()+MathSam.eval(inputScreen.getText()));
			}
			if(e.getActionCommand().equals("clear")==true)
			{
				inputScreen.setText("0");
				count=0;
			}
			if(e.getActionCommand().equals("reset")==true)
			{
				Windows window1 = new Windows("计算器");//但操作过多就会有很多的对象,内存占用,所以这里可以优化
			}
		}	
}




//科学型界面面板
package Calculator_advance;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Panel2 extends JFrame implements ActionListener{
	JLabel inputScreen = new JLabel();
	int count=0;
	String str;
	Panel2(String s)
	{
		setTitle(s);			
		setBounds(100,100,300,450);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	
		inputScreen.setSize(280,100);
		add(inputScreen,BorderLayout.NORTH);
		inputScreen.setText("0");
		inputScreen.setFont(new Font("SERIF",Font.BOLD,30));
		inputScreen.setHorizontalAlignment(JLabel.RIGHT);
		inputScreen.setBorder(BorderFactory.createLineBorder(Color.black));
		JPanel ButtonContainer = new JPanel();
		add(ButtonContainer);
		
		String Buttonnumbers[] = 
			   {"clear","reset",
			    "sqrt","abs","sin","cos", 
                "log","(",")","-",
                "6","7","8","9",
                "2","3","4","5",
                "0","1",".","="};
		for(String string:Buttonnumbers)
		{
			JButton button = new JButton(string);
			if(string =="clear" || string =="reset")
				button.setPreferredSize(new Dimension(120,50));
			else if(string !="clear" && string!="0" && string!="1" && string!="=" &&string!="reset" &&string!="-")
				button.setPreferredSize(new Dimension(60,50));
			else
				button.setPreferredSize(new Dimension(60,50));		
			ButtonContainer.add(button);
			
				
			button.addActionListener(this);
		}
		setVisible(true);	
		validate();	
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		MathComplexOperation MathCom =new MathComplexOperation();
		
		count++;
		if(count==1)
		  inputScreen.setText("");//不显示0
		
		if(e.getActionCommand()!="=")
		  inputScreen.setText(inputScreen.getText()+e.getActionCommand());
		else 
		{
			inputScreen.setText(inputScreen.getText()+"=");
			inputScreen.setText(inputScreen.getText()+MathCom.eval(inputScreen.getText()));
		}
		if(e.getActionCommand().equals("clear")==true)
		{
			inputScreen.setText("0");
			count=0;
		}
		if(e.getActionCommand().equals("reset")==true)
		{
			Windows window2 = new Windows("计算器");//但操作过多就会有很多的对象,内存占用,所以这里可以优化
		}
		}	
	}




//基本型算术运算操作类
package Calculator_advance;

import java.util.Scanner;

public class MathSampleOperation {

	public String str;
	
	public double eval(String str)//此处划分可以再优化
	{
		int i;
		int k=0;       //新操作符数组的操作符个数
		int count=0;   //次数标记
		double sum=0;  //乘除过程中的和
		double[] number = new double[20];
		String[] strArray =new String[20];
		
		double[] newnumber = new double[20];  //新数值数组
		String[] newstrArray =new String[20]; //新操作符数组-只含有 + -
		
	    String[] strnum = str.split("[\\p{Punct}]+");
	    String[] strstr = str.split("[\\d]+");
	    
	    /**********输出部分均为分步过程测试***********/
	    
	    for(i=0;i

第一张图短一些,因为有些信息在,不方便显示,所以就截掉了

Java实现计算器——升级记录中19.5.14……_第3张图片Java实现计算器——升级记录中19.5.14……_第4张图片Java实现计算器——升级记录中19.5.14……_第5张图片

 

/*************************************************************************/

19.5.24:

上面的程序实际跑出来后可以知道,每一次的reset,每一次的切换界面都会生成新的对象,导致后期内存负担增加,经过和别人交流,再次改进界面,不改动运算处理的两个类,主要是通过Container类来实现面板的切换的;

//主函数
package Calculator_advance;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
public class Calculator_advance {

	JMenuBar menubar;
	JMenu menu;
	JMenuItem item1,item2,item3;
	public static void main(String[] args) {
		 new Windows();
	}
}



//windows类
package Calculator_advance;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Windows extends JFrame {
	JMenuBar menubar;
	JMenu menu;
	JMenuItem item1,item2,item3;
	
	JLabel inputScreen = new JLabel();
	int count=0;    //无数据时显示0的标志位
	String str;           
//	JTextArea 允许多行编辑
	JTextArea HelloText = new JTextArea(
			  "Hello, welcome to use!                                 "
			  +"Choose the left upper corner",100,100);
	
	public Windows() {
		
		setBounds(100,100,300,470);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//第一种:菜单选择
		menubar = new JMenuBar();
		menu = new JMenu("模式选择");
		item1 = new JMenuItem("基本型",new ImageIcon("open.PNG"));
		item2 = new JMenuItem("科学型",new ImageIcon("open.PNG"));
		item3 = new JMenuItem("退出",new ImageIcon("close.PNG"));
		menu.add(item1);
		menu.add(item2);
		menu.add(item3);
		menubar.add(menu);
		setJMenuBar(menubar);
		
		
		inputScreen.setSize(280,100);
		add(inputScreen,BorderLayout.NORTH);
		inputScreen.setText("0");
		inputScreen.setFont(new Font("SERIF",Font.BOLD,40));
		inputScreen.setHorizontalAlignment(JLabel.RIGHT);
		inputScreen.setBorder(BorderFactory.createLineBorder(Color.black));		
		JPanel ButtonContainer = new JPanel();
		
		//Panel1
		JPanel panel1 = new JPanel();
		setTitle("基本型");					
		
		String Buttonnumbers[] = {"7","8","9","+", 
				                  "4","5","6","-", 
				                  "1","2","3","*", 
				                  "0",".","/","=",
				                  "(",")","←","C",};
		
		for(String string:Buttonnumbers)
		{
			JButton b = new JButton(string);
			
		    b.setPreferredSize(new Dimension(60,60));

			panel1.add(b);//添加组件
			
			b.addActionListener(new ActionListener(){
				
				@Override
				public void actionPerformed(ActionEvent e) {
				
					MathSampleOperation MathSam =new MathSampleOperation();
					
					count++;
					if(count==1)
						inputScreen.setText(e.getActionCommand());//直接显示键值					
					else 
					{
						if(e.getActionCommand()=="=")
					    {
							inputScreen.setText(inputScreen.getText()+"=");
						    inputScreen.setText(inputScreen.getText()+MathSam.eval(inputScreen.getText()));
					    }		
					    else if(e.getActionCommand().equals("C")==true)
					    {
					    	inputScreen.setText("0");
						    count=0;
					    }
					    else if(e.getActionCommand().equals("←")==true)
					    {
						    String str = inputScreen.getText();						    
						    if(str.length() - 1 > 0)
						    {
						       str = str.substring(0,str.length() - 1);//提取字符串从start-end的字符
							   inputScreen.setText(str);
							   count=0;
						    }
						    else 
							   inputScreen.setText("0");
					    }
					    else 
						    inputScreen.setText(inputScreen.getText()+e.getActionCommand());
					}
				}		
			});
		}
	
		//panel2
		JPanel panel2 = new JPanel();	
		setTitle("科学型");	
		String Buttonnumbers_Panel2[] = 
			   {"C","←",
			    "sqrt","abs","sin","cos", 
                "log","(",")","-",
                "6","7","8","9",
                "2","3","4","5",
                "0","1",".","="};
		for(String string:Buttonnumbers_Panel2)
		{
			JButton button = new JButton(string);
			if(string =="C" || string=="←")
				button.setPreferredSize(new Dimension(120,50));
			else
				button.setPreferredSize(new Dimension(60,50));		
			panel2.add(button);
			//组件监听
			button.addActionListener(new ActionListener() {		
				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					MathComplexOperation MathCom =new MathComplexOperation();	
					count++;
					if(count==1)
					{
						if(e.getActionCommand().equals("←")==false)
							inputScreen.setText(e.getActionCommand());//不显示0
						else
						{
							inputScreen.setText("0");//显示0
						    count=0;
						}
					}
					  
					else 
					{
						if(e.getActionCommand().equals("C")==true)
						{
							inputScreen.setText("0");
							count=0;   }
						else if(e.getActionCommand().equals("←")==true)
						{
							String str = inputScreen.getText();						    
						    if(str.length() - 1 > 0)
						    {
						       str = str.substring(0,str.length() - 1);//提取字符串从start-end的字符
							   inputScreen.setText(str);
						    }
						    else 
						    {
							   inputScreen.setText("0");
							   count=0; }					    
						}					
						else if(e.getActionCommand().equals("=")==true)
						{
							inputScreen.setText(inputScreen.getText()+"=");
							inputScreen.setText(inputScreen.getText()+MathCom.eval(inputScreen.getText()));
						}
						else
							inputScreen.setText(inputScreen.getText()+e.getActionCommand());
					}			
				}
			});
		}	
		validate();
		//初始化界面	
		Container currentPanel = getContentPane();	
		currentPanel.add(panel1);		
		/*
		 * 菜单栏事件处理
		 */
		item1.addActionListener(new ActionListener() {
			   public void actionPerformed(ActionEvent e) 
			   {			
				   currentPanel.remove(panel2);
				   currentPanel.add(panel1);
				   currentPanel.revalidate();
				   currentPanel.repaint();
			   }
		   });
		item2.addActionListener(new ActionListener() {
			   public void actionPerformed(ActionEvent e) 
			   {		
				   currentPanel.remove(panel1);;
				   currentPanel.add(panel2);
				   currentPanel.revalidate();
				   currentPanel.repaint();
			   }
		   });
		item3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) 
			{
				System.exit(0);//退出
			}
		});				
		setVisible(true);	
		validate();
	}
}

 

 

/*************************************************************************/

19.5.25

初步学习《代码重构》发现自己的window类里内容太多,功能不专一,且不适合于改动。

重构的本质——>

1. “重构技术就是以微小的步伐修改程序,如果你犯下错误,很容易便可以发现它”;

2. “变量名称是代码清晰的关键”;

3. “代码应该表现自己的目的”,每一个类都应该有自己最主要的功能

两个运算操作的类不变

//主函数
package calculatorRefactor;

public class Calculator {

	public static void main(String[] args) {
		
		 new WindowsInit();	//面盘初始化并选择
	}

}



//第一个类
/*
 * 初始化面盘内容并选择
 */
package calculatorRefactor;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

public class WindowsInit extends JFrame {
	JMenuBar menubar;
	JMenu menu;
	JMenuItem item1,item2,item3;
	
	JLabel inputScreen = new JLabel();
	int count=0;            //无数据时显示0的标志位
	String str;           
	static int chooseFlag=1;//静态变量需要类名引用——>基本型和科学型转换
	
	public WindowsInit() {
		
		setBounds(100,100,300,470);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		/*
		 * 菜单选择模式
		 */
		menubar = new JMenuBar();
		menu = new JMenu("模式选择");
		item1 = new JMenuItem("基本型",new ImageIcon("open.PNG"));
		item2 = new JMenuItem("科学型",new ImageIcon("open.PNG"));
		item3 = new JMenuItem("退出",new ImageIcon("close.PNG"));
		menu.add(item1);
		menu.add(item2);
		menu.add(item3);
		menubar.add(menu);
		setJMenuBar(menubar);
		
		
		inputScreen.setSize(280,100);
		add(inputScreen,BorderLayout.NORTH);
		inputScreen.setText("0");
		inputScreen.setFont(new Font("SERIF",Font.BOLD,40));
		inputScreen.setHorizontalAlignment(JLabel.RIGHT);
		inputScreen.setBorder(BorderFactory.createLineBorder(Color.black));		

		
		/*
		 * Panel1初始化
		 */
		JPanel panel1 = new JPanel();
		setTitle("基本型");					
		PanelComponent panel = new PanelComponent(inputScreen);
		panel.panel1(panel1, inputScreen);
		/*
		 * panel2初始化
		 */
		JPanel panel2 = new JPanel();	
		setTitle("科学型");	
		panel.panel2(panel2, inputScreen);

		/*
		 * 初始化界面选择	
		 */
		Container currentPanel = getContentPane();	
		currentPanel.add(panel1);
		
		/*
		 * 菜单栏事件处理
		 */
		item1.addActionListener(new ActionListener() {
			   public void actionPerformed(ActionEvent e) 
			   {			
				   currentPanel.remove(panel2);
				   currentPanel.add(panel1);
				   currentPanel.revalidate();
				   currentPanel.repaint();
				   WindowsInit.chooseFlag=1;//基本型运算
			   }
		   });
		item2.addActionListener(new ActionListener() {
			   public void actionPerformed(ActionEvent e) 
			   {		
				   currentPanel.remove(panel1);;
				   currentPanel.add(panel2);
				   currentPanel.revalidate();
				   currentPanel.repaint();
				   WindowsInit.chooseFlag=2;//科学型运算
			   }
		   });
		item3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) 
			{
				System.exit(0);//退出
			}
		});				
		/*
		 * 面盘显示
		 */
		setVisible(true);	
		validate();
	}
}




//第二个类
/*
 * 面盘组件添加类,封装成函数
 */
package calculatorRefactor;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class PanelComponent extends JFrame implements ActionListener{
	int count=0;

	private JLabel inputScreen;  
	
	SampleOperation MathSam =new SampleOperation();
	ComplexOperation MathCom =new ComplexOperation();
	/*
	 * panel1组件
	 */
	PanelComponent(JLabel inputScreen)
	{
		this.inputScreen=inputScreen;
	}
	
	public void panel1(JPanel panel1,JLabel inputScreen)
	{				
		
		String Buttonnumbers[] = {"7","8","9","+", 
				                  "4","5","6","-", 
				                  "1","2","3","*", 
				                  "0",".","/","=",
				                  "(",")","←","C",};		
		for(String string:Buttonnumbers)
		{
			
			JButton b = new JButton(string);
			
		    b.setPreferredSize(new Dimension(60,60));

			panel1.add(b);//添加组件
			
			b.addActionListener(this);			
		}	
	}
	
	
	/*
	 * panel2组件
	 */
	public void panel2(JPanel panel2,JLabel inputScreen)
	{
		String Buttonnumbers_Panel2[] = 
			   {"C","←",
			    "sqrt","abs","sin","cos", 
             "log","(",")","-",
             "6","7","8","9",
             "2","3","4","5",
             "0","1",".","="};
		
		for(String string:Buttonnumbers_Panel2)
		{
			
			JButton button = new JButton(string);
			if(string =="C" || string=="←")
				button.setPreferredSize(new Dimension(120,50));
			else
				button.setPreferredSize(new Dimension(60,50));		
			panel2.add(button);
			
			button.addActionListener(this);			
	    }
	}

    /*
     * 事件监听
     */
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
	
		count++;
		if(count==1)
		{
			if(e.getActionCommand().equals("←")==false)
				inputScreen.setText(e.getActionCommand());//不显示0
			else
			{
				inputScreen.setText("0");//显示0
			    count=0;
			}
		}
		else 
		{
			if(e.getActionCommand().equals("C")==true)
			{
				inputScreen.setText("0");
				count=0;   }
			else if(e.getActionCommand().equals("←")==true)
			{
				String str = inputScreen.getText();						    
			    if(str.length() - 1 > 0)
			    {
			       str = str.substring(0,str.length() - 1);//提取字符串从start-end的字符
				   inputScreen.setText(str);
			    }
			    else 
			    {
				   inputScreen.setText("0");
				   count=0; }					    
			}	
			//基本型和科学型的运算转换  WindowsInit.chooseFlag
			else if(e.getActionCommand().equals("=")==true && WindowsInit.chooseFlag==2)
			{
				inputScreen.setText(inputScreen.getText()+"=");
				inputScreen.setText(inputScreen.getText()+MathCom.eval(inputScreen.getText()));
			}
			else if(e.getActionCommand().equals("=")==true && WindowsInit.chooseFlag==1)
			{
				inputScreen.setText(inputScreen.getText()+"=");
				inputScreen.setText(inputScreen.getText()+MathSam.eval(inputScreen.getText()));
			}
			else
				inputScreen.setText(inputScreen.getText()+e.getActionCommand());
		}
	}
}


//基本型操作运算类(沿用以前)


//科学型操作运算类(沿用以前)

/*************************************************************************/

改进加入括号的算法:

浏览其网上他人的实现过程,发现其实有一种更普遍和接受的算法,即后缀表达式/逆波兰式;

打算有时间尝试一下

 

你可能感兴趣的:(Java)