用VB制作计算机,怎样写这个程序
简单的VB计算器代码:
'变量定义说明部分
Dim x1 As Single, x2 As Single
Dim Y As Single
Dim n As Integer '标记使用运算符类型
'接收数据输入
Private Sub Command1_Click(Index As Integer)
Text1.Text = Text1.Text + CStr(Index)
End Sub
'按运算符时的处理方法
Private Sub Command3_Click(Index As Integer)
x1 = Val(Text1.Text)
Text1.Text = ""
n = Index
End Sub
'输入小数点时的处理办法
Private Sub Command2_Click()
Text1.Text = Text1.Text + "."
End Sub
'单击退格按钮时的处理方法
Private Sub Command4_Click()
Text1.Text = Mid(Text1.Text, 1, Len(Text1.Text) - 1)
End Sub
'单击清除按钮时的处理方法
Private Sub Command5_Click()
x1 = 0: x2 = 0: Y = 0
Text1.Text = ""
End Sub
'单击退出按钮时的处理方法
Private Sub Command6_Click()
Unload Me
End Sub
'单击"="按钮时的处理方法
Private Sub Command7_Click()
x2 = Val(Text1.Text)
On Error GoTo err1
Select Case n
Case 0
Y = x1 + x2
Case 1
Y = x1 - x2
Case 2
Y = x1 * x2
Case 3
Y = x1 / x2
End Select
Text1.Text = CStr(Y)
Exit Sub
err1:
MsgBox "您输入的数据有误,请重新输入!", vbOKOnly + vbCritical, "错误!"
Text1.Text = ""
x1 = 0: x2 = 0: Y = 0
Exit Sub
End Sub
运行界面如下:
import javax.swing.*;
import java.awt.event.*;
class LayoutFrame extends JFrame{
private JLabel label1=new JLabel("操作数1:",JLabel.LEFT);
private JTextField jtf1;
private JLabel label2=new JLabel("操作数2:",JLabel.LEFT);
private JTextField jtf2;
private JLabel label3=new JLabel("答案:",JLabel.LEFT);
private JTextField jtf3;
public LayoutFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(10,20,300,400);
this.setLayout(new BorderLayout());
this.setVisible(true);
JPanel b1=new JPanel();
this.add(b1,BorderLayout.NORTH);
jtf1=new JTextField(5);
jtf2=new JTextField(5);
jtf3=new JTextField(5);
b1.add(label1);
b1.add(jtf1);
b1.add(label2);
b1.add(jtf2);
b1.add(label3);
b1.add(jtf3);
JPanel b2=new JPanel();
this.add(b2,BorderLayout.SOUTH);
JButton jia=new JButton("+");
JButton jian=new JButton("-");
JButton cheng=new JButton("*");
JButton chu=new JButton("/");
b2.add(jia);
b2.add(jian);
b2.add(cheng);
b2.add(chu);
jia.addActionListener(new MyAction());
jian.addActionListener(new MyAction());
cheng.addActionListener(new MyAction());
chu.addActionListener(new MyAction());
}
class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
Integer a=Integer.parseInt(jtf1.getText());
Integer b=Integer.parseInt(jtf2.getText());
if(e.getActionCommand().equals("+")){
jtf3.setText(""+a+"+"+b+"="+(a+b));
}
if(e.getActionCommand().equals("-")){
jtf3.setText(""+a+"-"+b+"="+(a-b));
}
if(e.getActionCommand().equals("*")){
jtf3.setText(""+a+"*"+b+"="+(a*b));
}
if(e.getActionCommand().equals("/")){
jtf3.setText(""+a+"/"+b+"="+(a/b));
}
}
}
}
class LayoutDemo {
public static void main (String[] args) {
new LayoutFrame();
}
}