编写GUI程序,用户在图形界面输入任意n,计算得出1+2+…+n的值
我给你写下
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SumFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = -3059616600875760053L;
JLabel lable, labTotal;
JTextField textLable, textTotal;
static JButton butSummation;
public SumFrame() {
lable = new JLabel("輸入n");
labTotal = new JLabel("前n项和");
textLable = new JTextField("", 10);
textTotal = new JTextField("", 10);
butSummation = new JButton("计算");
lable.setBounds(30, 30, 120, 30);
textLable.setBounds(180, 30, 120, 30);
labTotal.setBounds(30, 130, 120, 30);
textTotal.setBounds(180, 130, 120, 30);
butSummation.setBounds(160, 180, 120, 30);
add(lable);
add(textLable);
add(labTotal);
add(textTotal);
add(butSummation);
setLayout(null);
setBounds(200, 100, 400, 300);
// 窗口在屏幕中间显示
setLocationRelativeTo(null);
setTitle("求总量");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
SumFrame summationForm = new SumFrame();
butSummation.addActionListener(summationForm);
summationForm.add(butSummation);
}
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource();
if (jb == butSummation) {
String Mathematics = textLable.getText();
try {
int a = Integer.parseInt(Mathematics);
int sum=0;
for(int i=1;i<=a;i++){
sum+=i;
}
textTotal.setText(String.valueOf(sum));
} catch (Exception e2) {
JOptionPane.showMessageDialog(this, "输入的格式错误!", "提示对话框", JOptionPane.DEFAULT_OPTION);
}
}
}
}
import java.util.Scanner;
public class App4_8 {
public static void main(String[] args) {
int n,i=1,sum=0;
Scanner buf=new Scanner(System.in);
do{
System.out.println("请输入正整数:");
n=buf.nextInt();
}while(n<=0);//要求输入的n必须大于0,否则一直要求重新输入
while(i<=n)
sum+=i++;//计算和
System.out.println("1+2+...+"+n+"="+sum);//输出结果
}
}