摩尔的Java学习笔记4.1
第四周作业:
1、(抽象类)1)定义shape抽象类,包含求面积和求周长的方法;2)定义Circle类和Rectangle类继承shape类;3)定义Square类继承Rectangle类;4)运行时,让用户选择输入图形的种类,然后输入相应数据,求出该图形的面积和周长;
2、(数组)课程管理每学期都要开设多门课程,每门课程的信息包括课程名称、是否是必修课、授课教师、学时、学分;编程实现对课程信息进行创建、添加、删除、修改和查询操作;可以按课程名、是否是必修课、授课教师来进行查询;修改或删除之前要先查询;第五周作业:
3、(接口)1)定义shape接口,包含求面积和求周长的方法;2)定义Circle类、Rectangle类、Square类;3)要求Circle类和Rectangle类实现shape接口,Square类继承Rectangle类;4)运行时,让用户选择输入什么图形,然后输入相应数据,求出该图形的面积和周长;
4、(向量)课程管理 每学期都要开设多门课程,每门课程的信息包括课程名称、是否是必修课、授课教师、学时、学分;编程实现对课程信息进行创建、添加、删除、修改和查询操作;可以按课程名、是否是必修课、授课教师来进行查询;修改或删除之前要先查询。
1、(抽象类)1)定义shape抽象类,包含求面积和求周长的方法;2)定义Circle类和Rectangle类继承shape类;3)定义Square类继承Rectangle类;4)运行时,让用户选择输入图形的种类,然后输入相应数据,求出该图形的面积和周长;
/**
* @author 薛莲婷
*1)定义shape抽象类,包含求面积和求周长的方法;
*2)定义Circle类和Rectangle类继承shape类;
*3)定义Square类继承Rectangle类;
*4)运行时,让用户选择输入图形的种类,然后输入相应数据,求出该图形的面积和周长
*/
import java.util.*;
abstract class Shape{ //抽象类Shape
abstract float getArea(); //求面积
abstract float getCircumference(); //求周长
}
class Circle extends Shape{ //Circle类
private final float PI=3.14f;
protected float radius;
Circle(){} //Circle类构造方法
Circle(float r){
radius=r;
}
public float getArea(){ //Circle类求面积
return PI*radius*radius;
}
public float getCircumference(){ //Circle类求周长
return 2*PI*radius;
}
}
class Rectangle extends Shape{ //Rectangle类
protected float width;
protected float height;
Rectangle(){} //Rectangle类构造方法
Rectangle(float width,float height){
this.width=width;
this.height=height;
}
public float getArea(){ //Rectangle类求面积
return width*height;
}
public float getCircumference(){ //Rectangle类求周长
return 2*(width+height);
}
}
class Square extends Rectangle{ //Square类,继承Rectangle类
Square(){} //Square类构造方法
Square(float length){
super(length,length);
}
}
class ShapeCalculate {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Shape shape=null;
//得写“null”,不然输出句会显示说shape:“The local variable shape may not have been initialized”,它是考虑到else中没有初始化shape对象,虽然从我们的逻辑上看在运行中是不会有这样的问题的……
int y;
do{
y=0;
System.out.println("请选择输入的图形:1、圆形,2、矩形,3、正方形:");
int x=sc.nextInt();
//圆形
if(x==1){
System.out.println("请输入圆形的半径:");
float radius=sc.nextFloat();
shape=new Circle(radius);
}
//矩形
else if(x==2){
System.out.println("请输入矩形的长和宽,以空格相隔:");
float width=sc.nextFloat();
float height=sc.nextFloat();
shape=new Rectangle(width,height);
}
//正方形
else if(x==3){
System.out.println("请输入正方形的边长:");
float length=sc.nextFloat();
shape=new Square(length);
}
//输入错误
else{
y=1;
System.out.println("输入错误,请重新输入:");
}
}
while(y==1);
System.out.println("面积:"+shape.getArea()+"\t\t周长:"+shape.getCircumference());
sc.close();
}
}