Java语言编程复习题答案.doc
文本预览下载声明
Java语言编程复习题
编写如下求阶乘的方法:
long fact1( int n ) { }
在main()方法中调用这个方法求1!到10!的阶乘并显示
解:在文件“Ex2.java”中编写如下程序:
public class Ex2
{ public static void main( String[] args )
{ long sum=0 ;
for( int i=0 ; i=9 ; i++ )
sum+=fact1(i) ;
System.out.println(“1!+2!+3!+4!+5!+6!+7!+8!+9!+10!= ”+sum) ; }
public static long fact1( int n )
{ long s=1 ;
for (int i=1 ; i=n ; i++ )
s=s*i ;
return s ;
}
}
如下图所示的运算器界面:
在“public void actionPerformed(ActionEvent e) { }”方法体的定义中实现下面要求的功能:
当单击数字或点按钮时,其标签的内容按照从左到右的顺序显示在已定义好的成员变量“文本框”--- tf 中;
当单击“+”、“-”、“*”、“\”按钮后,将“文本框”--- tf 中显示的内容保存到已定义好的成员变量x中,然后将其清空,且将按钮上的标签符号保存在字符型成员变量c中;
当单击“=”按钮后,将根据输入的数据和c中保存的运算符做运算,然后将结果显示在已定义好的成员变量“文本框”--- tf 中;
JTextField jtf=new JTextField() ;
double x ;
char c ;
public void actionPerformed(ActionEvent e)
{ double y ,z ; String str ;
switch(e.getActionCommand().charAt(0))
{ case 0: case 1: case 2: case 3: case 4:
case 5: case 6: case 7: case 8: case 9: case .:
jtf.setText(jtf.getText()+e.getActionCommand()) ; break ;
case +: str=jtf.getText() ; x=Double.parseDouble(str) ; c=+ ; jtf.setText() ; break ;
case -: str=jtf.getText() ; x=Double.parseDouble(str) ; c=- ; jtf.setText() ; break ;
case *: str=jtf.getText() ; x=Double.parseDouble(str) ; c=* ; jtf.setText() ; break ;
case /: str=jtf.getText() ; x=Double.parseDouble(str) ; c=/ ; jtf.setText() ; break ;
case =:str=jtf.getText() ; y=Double.parseDouble(str) ;
switch(c)
{case +: z=x+y ; jtf.setText(Double.toString(z)) ; break ;
case -: z=x-y ; jtf.setText(Double.toString(z)) ; break ;
case *: z=x*y ; jtf.setText(Double.toString(z)) ; break ;
case /: z=x/y ; jtf.setText(Double.toString(z)) ; break ;
}
}
}
3、声明一个Circle1类,其有private型成员变量 radius,记录圆的半径;为radiua赋初值的一个参数的构造函数,以及public型的方法area( ) 和toString( ),其中第一个方法area( )实现计算圆的面积并返回面积的值,第二个方法toString( )实现把圆的半径及面积以适当形式表现出来并转化为字符串,最后返回该字符串。编写应用程序测试该Circle1类。要求程序运行时从键盘接收半径数据,再以该半径为参数生成一
显示全部