d=a>b?(a>c?a:c):(b>c?b:c); System.out.println("最多数为:"+d); } } 5简单计算器的小程序 package one; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Jsq implements ActionListener { private JFrame frame; private JButton[] bus; private JTextField jtx; private JButton bu; private char[] strs; private String d_one = ""; private String operator; public static void main(String[] args) { new Jsq(); }
/* 利用构造进行实例化 */ public Jsq() { frame = new JFrame("计算器"); jtx = new JTextField(14); bus = new JButton[16]; strs = "789/456*123-0.+=".toCharArray(); for (int i = 0; i < 16; i++) { bus[i] = new JButton(strs[i] + ""); bus[i].addActionListener(this); } bu = new JButton("C"); bu.addActionListener(this); init(); } /* GUI 初始化 */ public void init() { JPanel jp1 = new JPanel(); jp1.add(jtx); jp1.add(bu); frame.add(jp1, BorderLayout.NORTH); JPanel jp2 = new JPanel(); jp2.setLayout(new GridLayout(4, 4)); for (int i = 0; i < 16; i++) { jp2.add(bus[i]); } frame.add(jp2, BorderLayout.CENTER); frame.pack(); frame.setLocation(300, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /* 事件的处理 */ public void actionPerformed(ActionEvent arg0) { /*获取输入字符*/ String conn = arg0.getActionCommand(); /*清除计算器内容*/ if ("C".equals(conn)) {
d_one = ""; operator = ""; jtx.setText(""); return; } /*暂未实现该功能*/ if(".".equals(conn)){ return; } /*记录运算符,保存运算数字*/ if (("+-*/".indexOf(conn)) != -1) { if("".equals(d_one) && "".equals(jtx.getText())) return; d_one = jtx.getText(); operator = conn; jtx.setText(""); return; } /*计算结果*/ if ("=".equals(conn)) { if("".equals(d_one) && "".equals(jtx.getText())) return; double db = 0; if ("+".equals(operator)) { db = Double.parseDouble(d_one) + Double.parseDouble(jtx.getText()); jtx.setText(db + ""); } if ("-".equals(operator)) { db = Double.parseDouble(d_one) - Double.parseDouble(jtx.getText()); jtx.setText(db + ""); } if ("*".equals(operator)) { db = Double.parseDouble(d_one) * Double.parseDouble(jtx.getText()); jtx.setText(db + ""); } if ("/".equals(operator)) { db = Double.parseDouble(d_one) / Double.parseDouble(jtx.getText()); jtx.setText(db + ""); } d_one = db + ""; return; }
//界面显示 jtx.setText(jtx.getText() + conn); } }{:2_31:} |
|