如何用JAVA编写一个类,该类创建的对象可以计算等差数列的和?

来源:百度知道 编辑:UC知道 时间:2024/05/11 01:39:38
刚学JAVA请高手指教!

class calculate
{
private int t,s;
public void calculate()
{
s=0;
}
/*
参数:数列开始,最后一位,增量
返回:int
*/
public int total(int first,int last,int increment)//increment为数列增量
{
if( ((last - first) / increment) % 1 ==0 ) //数列为等差时
{
for(int j=0;j<(last - first) / increment + 1;j++)
{
t = j*increment + first;
s = s + t;
}
}
return s;
}
}
//测试
class test4
{
public static void main(String args[])
{
calculate c = new calculate();//这里创建一个对象
System.out.println(c.total(1,9,4)); //这里调用C对象的total方法
}
}