【简答题】
本题程序的功能是定义一个简单的计算器,可以进行基本的四则运算。程序中布局了16个按钮用来表示数字0~9及运算符和点号,程序顶部的文本框用来显示运算数及结果。请将下述程序补充完整(注意:不得改动程序的结构,不得增行或删行)。
import java.awt.*;
import java.awt..*;
import javax.swing.*;
public class
public static void main (String[] args)
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch (Exception e)
JFrame frame = new CalculatorFrame();
frame.show();
class CalculatorPanel extends JPanel implements ActionListener
private JTextField display;
private JButton btn;
private double arg = 0;
private String op = "=";
private boolean start = true;
public CalculatorPanel()
setLayout(new BorderLayout());
display = new JTextField("0");
display.setEditable(false);
add(display,"North");
JPanel p = new JPanel();
p.setLayout(new GridLayout(4,4));
String buttons = "789/456"123-0.= +";
for (int i = 0; i < buttons.length(); i ++)
btn = new JButton(buttons.substring(i,i + 1));
p.add(btn);
______;
add(p,"Center");
public void actionPerformed(Action evt)
String s = evt.getActionCommand();
if (’0’< = s.charAt(0)&&s.charAt(0) <=’9’ ||s.equals("."))
if (start)
display.setText(s);
else
display.setText(display.getText() + s);
start = false;
else
if (start)
if (s.equals("-"))
display.setText(s);
start = false;
else
op = s;
else
double x =______;
calculate(x);
op = s;
start = true;
public void calculate(double n)
if (op.equals(" + "))
arg += n;
else
if(op.equals("-"))
arg - = n;
else
if(op.equals("*"))
arg *= n;
else
if(op.equals("/"))
arg /= n;
else
if(op.equals("="))
arg=n;
display.setText(""+ arg);
class CalculatorFrame extends Jframe
public CalculatorFrame()
setTitle("");
setSize(220,180);
addWindowListener(new WindowAdapter()
public void windowClosing(Window e)
System.exit(0);
);
Container contentPane=getContentPane();
contentPane.add(new CalculatorPanel());
手机使用
分享
复制链接
新浪微博
分享QQ
微信扫一扫
微信内点击右上角“…”即可分享
反馈
收藏
举报
参考答案:
参考解析: