Demo entry 6651512

cc

   

Submitted by lu on Oct 24, 2017 at 05:28
Language: Java. Code size: 7.3 kB.

package test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Stack;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class Calculator extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JTextField CTf = new JTextField("0");
    private JMenuBar CMenuBar = new JMenuBar();
    JMenu CMenu = new JMenu("鎷彿杈撳叆");
    private boolean Dflag = true;
    private double result = 0.0;
    private String operator = "=";
    private boolean flag = true;
	private final String[] Buttons = {"7", "8", "9", "梅", "%", "4", "5", "6", 
            "X", "1/x", "1", "2", "3", "锛�", "锛�", "卤", "0", ".", "=", "鈭�"};
    private JButton CButtons[] = new JButton[Buttons.length];
    
    public static void main(String args[]) {
    	Calculator calculatorTest = new Calculator();
    	
    	calculatorTest.setVisible(true);
    	calculatorTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public Calculator() {
    	super();
    	init();
    	try {
        	UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        	SwingUtilities.updateComponentTreeUI(this);
        } catch(Exception e) {
        	e.printStackTrace();
        }
    	this.setBackground(Color.BLACK);
    	this.setTitle("Calculator");
    	this.setLocation(640, 480);
    	this.setResizable(false);
    	this.pack();
    }
    
    private void init() {
    	int i;
    	CTf.setEditable(true);
    	CTf.setBackground(Color.PINK);
    	CTf.setHorizontalAlignment(JTextField.RIGHT);
    	
    	CMenuBar.add(CMenu);
    	JPanel ButtonsPanel = new JPanel();
    	ButtonsPanel.setLayout(new GridLayout(4, 5, 4, 4));
    	for (i = 0; i < Buttons.length; i++) {
    		CButtons[i] = new JButton(Buttons[i]);
    		ButtonsPanel.add(CButtons[i]);
    		CButtons[i].setForeground(Color.black);
    	}
    	
    	JPanel CPanel = new JPanel();
    	CPanel.setBackground(Color.PINK);
    	CPanel.add(CTf, BorderLayout.NORTH);
    	CPanel.add(ButtonsPanel);
    	
    	getContentPane().setLayout(new BorderLayout());
    	getContentPane().add("North", CMenuBar);
    	getContentPane().add("Center", CTf);
    	getContentPane().add("South", ButtonsPanel);
    	CMenu.addActionListener(this);
    	for (i = 0; i < Buttons.length; i++) {
    		CButtons[i].addActionListener(this);
    	}
        
    }
    
    public void actionPerformed(ActionEvent e) {
    	String ac = e.getActionCommand();
    	if ("0123456789.".indexOf(ac) >= 0) {
    		solve(ac);
  	    } else if (e.getSource() == CMenu) {
  	        compute(ac);
  	    }
    	else {
    		handleOperator(ac);
    	}
    }
    
    private void solve(String key) {
    	if (Dflag) {
    		CTf.setText(key);
    	} else if (key.equals(".") && (CTf.getText().indexOf(".") < 0)) {
    		CTf.setText(CTf.getText() + ".");
    	} else if (!key.equals(".")) {
    		CTf.setText(CTf.getText() + key);
    	}
    	Dflag = false;
    }
    
    private void handleOperator(String key) {
    	if (operator.equals("锛�")) {
    		result += getNumber();
    	} else if (operator.equals("锛�")) {
    		result -= getNumber();
    	} else if (operator.equals("X")) {
    		result *= getNumber();
    	} else if (operator.equals("%")) {
    		result /= 100;
    	} else if (operator.equals("卤")) {
    		result = -result;
    	} else if (operator.equals("=")) {
    		result = getNumber();
    	} else if (operator.equals("鈭�")) {
    		result = Math.sqrt(result);
    	}
    	else if (operator.equals("梅")) {
    		if (getNumber() == 0.0) {
    			flag = false;
    			CTf.setText("闄ゆ暟涓嶈兘涓�0!");
    		} else {
    			result /= getNumber();
    		}
    	} else if (operator.equals("1/x")) {
    		if (result == 0) {
    			flag = false;
    			CTf.setText("0娌℃湁瀵兼暟!");
    		} else {
    			result = 1 / result;
    		}
    	}
    	
    	if (flag) {
			long t1;
			double t2;
			t1 = (long) result;
			t2 = result - t1;
			if (t2 == 0) {
				CTf.setText(String.valueOf(t1));
			} else {
				CTf.setText(String.valueOf(result));
			}
		}
    	
    	operator = key;
    	Dflag = true;
    	flag = true;
    }
    
    private double getNumber() {
    	double num = 0.0;
    	try {
    		num = Double.valueOf(CTf.getText()).doubleValue();
    	} catch (NumberFormatException e) {
    	}
    	return num;
    }
    
    public void compute(String key) {
    	ArrayList postfix = new ArrayList();
    	postfix = transform(key);
    	int i, res = 0, size = postfix.size();
    	Stack<Integer> stack_num = new Stack<Integer>();
    	for (i = 0; i < size; i++) {
    		if (postfix.get(i).getClass() == Integer.class) {
    			stack_num.push((Integer)postfix.get(i));
    		} else {
    			int a = stack_num.pop();
    			int b = stack_num.pop();
    			switch((Character)postfix.get(i)) {
    			case '+':
    				res = b + a; break;
    			case '-':
    				res = b - a; break;
    			case '*':
    				res = b * a; break;	
    			case '/':
    				res = b / a; break;	
    			}
    			stack_num.push(res);
    		} 
    	}
    	res = stack_num.pop();
    	String s = "";
    	s = res+"";
    	CTf.setText(s);
    }
    
    public static ArrayList transform(String prefix) {
    	int i, len = prefix.length();
    	prefix = prefix + '#';
    	Stack<Character> stack = new Stack<Character>();
    	stack.push('#');
    	ArrayList postfix = new ArrayList();
    	for (i = 0; i < len + 1; i++) {
    		if (Character.isDigit(prefix.charAt(i))) {
    			if (Character.isDigit(prefix.charAt(i+1))) {
    				postfix.add(10 * (prefix.charAt(i) - '0') +
    				(prefix.charAt(i+1) - '0'));
    				i++;
    			} else {
    				postfix.add((prefix.charAt(i) - '0'));
    			}
    		} else {
    				switch (prefix.charAt(i)) {
    				case '(':
    					stack.push(prefix.charAt(i)); break;
    				case ')':
    					while (stack.peek() != '(')
    						postfix.add(stack.pop());
    					    stack.pop();
    					    break;
    					default:
    						while (stack.peek() != '#'
    						       && compare(stack.peek(), prefix.charAt(i)))
    							postfix.add(stack.pop());
    						if (prefix.charAt(i) != '#') {
    							stack.push(prefix.charAt(i));
    						}
    						break;
    				}
    			}
    		}
    	return postfix;
    	}
    	
    public static boolean compare(char peek, char cur) {
    	if (peek == '*'
    			&& (cur == '+' || cur == '-' || cur == '*') || cur == '/')
    		return true;
    	else if (peek == '/'
    			&& (cur == '+' || cur == '-' || cur == '*' || cur == '/'))
    		return true;
    	else if (peek == '+' && (cur == '+' || cur == '-')) 
    		return true;
    	else if (peek == '-' && (cur == '+' || cur == '-'))
    		return true;
    	else if (cur == '#')
    		return true;
    	return false;
    }
}

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).