java一些作业题
1.编写Java程序,创建两个类Computer和Test Computer,在Computer类中定义一个返回值为int型的方法totalSum(int from,int end)用于求两个参数之间所有整数和,然后再TestComputer类中创建Computer类的实例,并访问其方法totalSum(int from,int enf)求1~100的和并输出。
Computer类:
public class Computer {
public int totalSum(int a, int b){
if(a<b){
int sum=a+(a+1);
a=a+1;
return sum+totalSum((a+1),b);
}
else if (a==b){
return a;
}
else
return 0;
}
}
Test Computer类:
public class TestComputer {
public static void main(String[] args) {
Computer c=new Computer();
System.out.println(c.totalSum(1,100));
}
}
输出结果为:
2.编写Java程序,创建一个类Area,该类中有一个返回值为double型的方法setArea(double r)用于计算圆的面积,形参r表示圆的半径,然后创建一个类TestArea,并在该类的主方创建Area类的实例,并调用Area类的方法求出半径是20.5的圆的面积并输出。
Area类:
public class Area {
double r;
final double PI=3.14;
public double setArea(double r) {
return this.r=r;
}
public double s(){
return r*r*PI;
}
}
TestArea类:
public class TestArea {
public static void main(String[] args) {
Area ss=new Area();
double a=ss.setArea(20.5);
System.out.println(ss.s());
}
}
结果为:
3.编写Java 程序,创建一个形状的类Shape和一个表示圆形的类Circle,类Circle继承自类Shape,类Shape 中定义一个无返回值无参数的力法 showShape用于输出图形的形状,在类Circle中定义一个无返回打形参的力法prInUircle苹t这定丁类中的方法。”。然后在类 Circle 中创建类Shape和类 Circle的实例分鹏访问 showShape力云l. printCIrcle万法进行测试,然后把类Circle的实例赋值给类Shape的引用,并通过类shape的引用访问这两个方法进行测试。
package JiCheng;
public class Shape {
String name;
public void showShape(){
System.out.println("该形状为:"+this.name);
}
}
class Circle extends Shape{
public void printShape(){
System.out.println("这是子类的方法");
}
public static void main(String[] args) {
Shape shape=new Shape();
Circle circle=new Circle();
circle.name="圆形";
circle.printShape();
circle.showShape();
// shape.showShape();
Circle circle1=new Circle();
// circle.name="三角形";
Shape shape1=circle1;
// Circle circle2=(Circle)shape1;
shape1.name="三角形";
shape1.showShape();
((Circle) shape1).printShape();
}
}
结果为: