『壹』 (1) 編寫一個java程序實現兩數求和功能:在兩個文本框里分別輸入兩個數字,單擊「求和」按鈕,則在第三
效果如圖
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
{
JTextFieldjtf1,jtf2,jtf3;
publicAddFrame(){
//控制項的創建
jtf1=newJTextField(10);
JLabeljl=newJLabel("+");
jtf2=newJTextField(10);
JButtonjbAdd=newJButton("求和");
jbAdd.addActionListener(this);//給按鈕添加事件響應
jtf3=newJTextField(10);
jtf3.setEditable(false);//結果文本框不能被編輯
add(jtf1);
add(jl);
add(jtf2);
add(jbAdd);
add(jtf3);
setLayout(newFlowLayout());//窗口流式布局
setSize(458,95);
setTitle("求和");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
//當按鈕被點擊時執行actionPerformed方法
publicvoidactionPerformed(ActionEvente){
try{
doubled1=Double.parseDouble(jtf1.getText());
doubled2=Double.parseDouble(jtf2.getText());
jtf3.setText(""+(d1+d2));
}catch(Exceptionex){
JOptionPane.showMessageDialog(this,"提示:只能輸入兩個數字,不能為空或者其他字元");
}
}
publicstaticvoidmain(String[]args){
newAddFrame();//啟動窗口
}
}
『貳』 程序運行後在兩個文本框中分別輸入正整數a和b(a<=b)單擊確定按鈕,在文本框中顯示ab間所有素數
Public Class Form1
Function isprime(ByVal x As Integer) As Integer
Dim i As Integer
For i = 2 To x - 1
If x Mod i = 0 Then
Exit For
End If
Next i
If i >= x Then
isprime = 1
Else
isprime = 0
End If
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = ""
Dim a As Integer
Dim b As Integer
a = TextBox1.Text
b = TextBox2.Text
Dim x As Integer
For x = a To b
If isprime(x) = 1 Then
Label1.Text = Label1.Text + x.ToString() + ","
End If
Next x
End Sub
End Class