Workshop 2007 JRE Java Support
Installation
Home
CalcTool
Java Applets
Friends/Family
Gardening
Woodworking
Forums
double sum(double x){
	return x*(x+1)/2.0;
}
private void  computeButtonMouseClicked(java.awt.event.MouseEvent evt) {                                   
     int answer=0;
     int n=Convert.toInt(nField.getText());
           
     for (int i=1; i<=n; i++){
       answer+=i;
     }
     loopLabel.setText(""+answer);
     methodLabel.setText(""+sum(n));
     }
  

Note that I’m abusing the type of the variable n.  The method I’ve written requires a double argument.  But in the line

methodLabel.setText(""+sum(n));

I’ve inputted an int into the method sum(x). The compiler has detected this and deals with it, However, you will often get a compile-time error.when you don’t math types correctly.  In general, this is not good programming practice.

 

 

Sample Code 4