Lesson 4 Calculating Sequences

Points and Activities

  1. Buttons TextFields Labels
  2. Events
  3. Transforming integer|string
  4. Transforming double|string

Example 4 1+2+3+4+....+n

Screen of Applet

Exm4.java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Exm4 extends Applet implements ActionListener
{   
	TextField textField1 = new TextField(); //input textField
	TextField textField2 = new TextField(); //output textField
	Label label1 = new Label();
	Label label2 = new Label();
	Button button1 = new Button();
	
	public void init()
	{
		
		setLayout(null);  //free layout
		setSize(300,300); //size of this applet
		
		add(textField1);  
		textField1.setFont(new Font("Dialog", Font.PLAIN, 20));
		textField1.setBounds(100,50,150,40);
	    
		add(textField2);
		textField2.setFont(new Font("Dialog", Font.PLAIN, 20));
		textField2.setBounds(100,120,150,40);
		
		add(label1);
		label1.setText("n = ");
		label1.setFont(new Font("Dialog", Font.PLAIN, 20));
		label1.setBounds(20,50,60,40);
		
		add(label2);
		label2.setText("sum = ");
		label2.setFont(new Font("Dialog", Font.PLAIN, 20));
		label2.setBounds(20,120,60,40);
		
		add(button1);
		button1.setLabel("calculate");
		button1.setBackground(java.awt.Color.lightGray);
		button1.setFont(new Font("Dialog", Font.PLAIN, 20));
		button1.setBounds(80,200,120,40);
	    	button1.addActionListener(this);
	
	}
	

	public void actionPerformed(ActionEvent event)
	{
		Object object = event.getSource();
		String str;
		int n,sum;
		if (object == button1){
			 // get text from textfield 
		    	str=textField1.getText();
			// convert string to integer
			n=Integer.parseInt(str);  
			sum=calculate(n);
			// convert integer to string	
	        		str=Integer.toString(sum);	
			//set text to textfield
			textField2.setText(str);  
	    	}
	}
	
	public int calculate(int n){
	    	int i;  // index 
	    	int a;  // i-th term
	    	int s=0;  // sum of the sequence
	    	for(i=1;i<=n;i++){
	        		a=i;    //a(i)=i
	        		s=s+a;  // S(i+1)=S(i)+a(i)
	    	}
	    	return s;
	}	
}


Exm4.html
<HTML>
<HEAD>
<TITLE>Exm4</TITLE>
</HEAD>
<BODY>
<APPLET CODE="Exm4.class" WIDTH=300 HEIGHT=300></APPLET>
</BODY>
</HTML>


Excercise 4a Make an applet to calculate 1+1/2+1/3+1/4+......+1/n for given n.

Excercise 4b Sequence {an} is defined by an+11/2(an+5/anjand a1
Make an applet to calculate an by given a1 and n.