第二次博客作业

一、前言

对于这三次大作业来说,主要是考验我们在课堂上所学内容的掌握情况。以及对继承,接口以及多态的熟练运用,还有一点则是对正则表达式的训练。虽然题量不是很大,但每次要学习和掌握的新知识都特别多,这对刚入门java的我来说🦆🍐还是很大的/(ㄒoㄒ)/~~

二、设计与分析

题目集四  程序7-2

import java.util.Scanner;



//DateUtil类
class DateUtil{
    Day day;
    //默认构造方法
    public DateUtil(){
    }
    //带参构造方法
    public DateUtil(int d,int m,int y){
        this.day=new Day(d,m,y);
    }
    //getter
    public Day getDay(){
        return day;
    }
    //setter
    public void setDay(Day d){
        this.day=d;
    }

    //效验数据合法性
    public boolean checkInputValidity(){
        if(this.getDay().getMonth().getYear().validate()&&this.getDay().getMonth().validate()&&day.validate())
            return true;
        else
            return false;
    }
    //比较两个日期大小
    public boolean compareDates(DateUtil date) {
        if(date.getDay().getMonth().getYear().getValue()<this.getDay().getMonth().getYear().getValue())
            return false;
        else if(date.getDay().getMonth().getYear().getValue()==this.getDay().getMonth().getYear().getValue()&&date.getDay().getMonth().getValue()<this.getDay().getMonth().getValue())
            return false;
        else if(date.getDay().getMonth().getYear().getValue()==this.getDay().getMonth().getYear().getValue()&&date.getDay().getMonth().getValue()==this.getDay().getMonth().getValue()&&date.getDay().getValue()<this.getDay().getValue())
            return false;
        else
            return true;
    }
    //判定两个日期是否相等
    public boolean equalTwoDates(DateUtil date){
        if(this.getDay().getValue()==date.getDay().getValue()&&this.getDay().getMonth().getValue()==date.getDay().getMonth().getValue()&& this.getDay().getMonth().getYear().getValue()==date.getDay().getMonth().getYear().getValue())
            return true;
        else
            return false;
    }
    //日期值格式化
    public String showDate(){
        return this.getDay().getMonth().getYear().getValue()+"-"+this.getDay().getMonth().getValue()+"-"+this.getDay().getValue();
    }
    //计算该年的剩余天数
    public int syts(DateUtil d){
        int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
        int b=0,i;
        for(i=d.getDay().getMonth().getValue()+1;i<=12;i++){
            b=b+a[i];
        }
        b=b+a[d.getDay().getMonth().getValue()]-d.getDay().getValue();
        if(d.getDay().getMonth().getYear().isLeapYear()&&d.getDay().getMonth().getValue()<=2)//闰年
            b++;
        return b;
    }

public class Main {
    public static void main(String[] args) {
        Scanner x=new Scanner(System.in);
        int year=0,month=0,day=0,a,b;
        a=x.nextInt();//输入判断类型
        year=x.nextInt();month= x.nextInt();day=x.nextInt();//输入年月日
        DateUtil c=new DateUtil(year,month,day);
        if(a==1){//求下n天
            b=x.nextInt();//输入n
            if(!c.checkInputValidity()||b<0){//如果数据不合法
                System.out.println("Wrong Format");
                System.exit(0);
            }
            else
                System.out.println(c.getNextNDays(b).showDate());
        }
        else if(a==2){
            b=x.nextInt();//输入n
            if(!c.checkInputValidity()||b<0){//如果数据不合法
                System.out.println("Wrong Format");
                System.exit(0);
            }
            else

    public DateUtil getNextNDays(int n){
        int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
        int y=0,m=0,d=0;
        int i,j;
        int b=syts(this);//该年剩余天数
        if(b>n){//该年剩余天数大于n
            y=this.getDay().getMonth().getYear().getValue();
            if(this.getDay().getMonth().getYear().isLeapYear()){//如果是闰年
                a[2]=29;
            }
            int e=a[this.getDay().getMonth().getValue()];//该月的天数
            e=e-this.getDay().getValue();//本月剩余的天数
            if(e>=n){//如果n天后在本月
                m=this.getDay().getMonth().getValue();
                d=n+this.getDay().getValue();
            }
            else{//如果n天后不在本月
                n=n-e;
                m=this.getDay().getMonth().getValue()+1;
                i=m;
                while(n-a[i]>0&&i<=12){//找到月
                    n=n-a[i];
                    m++;
                    i++;
                }
                d=n;//找到天
            }
        }
        else{//该年剩余天数小于n
            n=n-b;
            y=this.getDay().getMonth().getYear().getValue()+1;
            int c=365;//平年天数
            if(new Year(y).isLeapYear()){//闰年天数
                c++;
            }
            while(n-c>0){//找到年
                n=n-c;
                y++;
                c=365;
                if(new Year(y).isLeapYear())
                    c++;
            }
            i=1;
            while(n-a[i]>0&&i<=12){//找到月
                n=n-a[i];
                i++;
            }
            m=i;
            d=n;//找到天
        }
        return new DateUtil(y, m, d);
    }
    //求前n天
    public DateUtil getPreviousNDays(int n){
        int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
        int y=0,m=0,d=0;
        int i,b;
        b=365-syts(this);//该日期所在年份已经过的天数
        if(this.getDay().getMonth().getYear().isLeapYear()){//如果是闰年
           b++;
        }
        if (b>n){//如果前n天在该年
            y=this.getDay().getMonth().getYear().getValue();
            int e=this.getDay().getValue();//本月已经过的天数
            if(e>n){//如果前n天在本月
                m=this.getDay().getMonth().getValue();
                d=e-n;
            }
            else{//如果前n天不在本月
                n=n-e;
                m=this.getDay().getMonth().getValue()-1;
                i=m;
                while(n-a[i]>0&&i>=0){//找到月
                    n=n-a[i];
                    m--;
                    i--;
                }
                d=a[i]-n;//找到天
                if(new Year(y).isLeapYear()&&m==2){
                    d++;
                }
            }
        }
        else{//如果前n天不在该年
            n=n-b;
            y=this.getDay().getMonth().getYear().getValue()-1;
            int f=365;
            if(new Year(y).isLeapYear()){
                f++;
            }
            while(n-f>0){//找到年
                n=n-f;
                y--;
                f=365;
                if(new Year(y).isLeapYear())
                    f++;
            }
            i=12;
            while(n-a[i]>0&&i>=0){//找到月
                n=n-a[i];
                i--;
            }
            m=i;
            d=a[i]-n;//找到天
            if(new Year(f).isLeapYear()&&m==2){
                d++;
            }
        }
        return new DateUtil(y, m, d);
    }
    //求两个日期之间的天数
    public int getDaysofDates(DateUtil date){
        DateUtil b1=this;
        DateUtil b2=date;
        if(this.equalTwoDates(date)){//如果两天的日期相等
            return 0;
        }
        else if(!this.compareDates(date)){//如果日期大小不对
            b1=date;
            b2=this;
        }
        int a[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
        int i,j,ts=0;
        for(i=b1.getDay().getMonth().getYear().getValue()+1;i<b2.getDay().getMonth().getYear().getValue();i++){//两个日期的年数之和
            ts=ts+365;
            if(new Year(i).isLeapYear())
                ts++;
        }
        if(b1.getDay().getMonth().getYear().getValue()==b2.getDay().getMonth().getYear().getValue()&&b1.getDay().getMonth().getValue()==b2.getDay().getMonth().getValue()){//年份相同,月份相同,日不同
            ts=b2.getDay().getValue()-b1.getDay().getValue();
        }
        else if(b1.getDay().getMonth().getYear().getValue()==b2.getDay().getMonth().getYear().getValue()&&b1.getDay().getMonth().getValue()!=b2.getDay().getMonth().getValue()){//年份相同,月份不同
            if(b1.getDay().getMonth().getYear().isLeapYear())//是闰年
                a[2]=29;
            ts=ts+a[b1.getDay().getMonth().getValue()]-b1.getDay().getValue();//小日期该月剩余的天数
            ts=ts+b2.getDay().getValue();//大日期的天数
            for(j=b1.getDay().getMonth().getValue()+1;j<=b2.getDay().getMonth().getValue()-1;j++)//月份天数和
                ts+=a[j];
        }
        else if(b1.getDay().getMonth().getYear().getValue()!=b2.getDay().getMonth().getYear().getValue()){//年份不同
            ts=ts+a[b1.getDay().getMonth().getValue()]-b1.getDay().getValue();//小日期在该月剩余的天数
            ts=ts+b2.getDay().getValue();//大日期在该月已经过的天数
            for(j=b1.getDay().getMonth().getValue()+1;j<=12;j++)//小日期在该年剩余的天数
                ts=ts+a[j];
            for(j=b2.getDay().getMonth().getValue()-1;j>0;j--)//大日期在该年已经过的天数
                ts=ts+a[j];
            if(b1.getDay().getMonth().getYear().isLeapYear()&&b1.getDay().getMonth().getValue()<=2)//如果小日期该年为闰年且该天在1月或2月
                ts++;
            if(b2.getDay().getMonth().getYear().isLeapYear()&&b2.getDay().getMonth().getValue()>2)//如果大日期该年为闰年且该天在1月或2月后
                ts++;
        }
        return ts;
    }
}
                System.out.println(c.getPreviousNDays(b).showDate());
        }
        else if(a==3){
            int y1,m1,d1;
            y1=x.nextInt();m1= x.nextInt();d1=x.nextInt();//输入第二个年月日
            DateUtil d=new DateUtil(y1,m1,d1);
            if(!c.checkInputValidity()||!d.checkInputValidity()){//如果数据不合法
                System.out.println("Wrong Format");
                System.exit(0);
            }
            else
                System.out.println(c.getDaysofDates(d));
        }
        else
            System.out.println("Wrong Format");

    }
}
class Year{
    int value;
    //默认构造方法
    public Year(){
    }
    //带参构造方法
    public Year(int value){
        this.value=value;
    }
    //getter
    public int getValue(){
        return value;
    }
    //setter
    public void setValue(int value){
        this.value=value;
    }
    //判断year是否为闰年
    public  boolean isLeapYear(){
        if((value%4==0&&value%100!=0)||value%400==0)
            return true;
        else
            return false;
    }
    //效验数据合法性
    public boolean validate(){
        if(value<=2050&&value>=1900)
            return true;
        else
            return false;
    }
    //年份加一
    public void yearIncrement(){
        value=value+1;
    }
    //年份减一
    public void yearReduction(){
        value=value-1;
    }
}
//Month类
class Month{
    int value;
    Year year;
    //默认构造方法
    public Month(){
    }
    //带参构造方法
    public Month(int yearValue,int monthValue){
        this.year=new Year(yearValue);
        this.value=monthValue;
    }
    //getter
    public int getValue(){
        return value;
    }
    public Year getYear(){
        return year;
    }
    //setter
    public void setValue(int value){
        this.value=value;
    }
    public void setYear(Year year){
        this.year=year;
    }
    //日期复位(1)
    public void resetMin(){
        value=1;
    }
    //月份设置为12
    public void resetMax(){
        value=12;
    }
    //效验数据合法性
    public boolean validate(){
        if(value>=1&&value<=12)
            return true;
        else
            return false;
    }
    //月份加一
    public void dayIncrement(){
        value=value+1;
    }
    //月份减一
    public void dayReduction(){
        value=value-1;
    }
}
//Day类
class Day{
    int value;
    Month month;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    //默认构造方法
    public Day(){
    }
    //带参构造方法
    public Day(int yearValue,int monthValue,int dayValue){
        this.month=new Month(yearValue,monthValue);
        this.value=dayValue;
    }
    //getter
    public int getValue(){
        return value;
    }
    public Month getMonth(){
        return month;
    }
    //setter
    public void setValue(int value){
        this.value=value;
    }
    public void setMonth(Month value){
        this.month=value;
    }
    //日期复位(1)
    public void resetMin(){
        value=1;
    }
    //日期设为该月最大值
    public void resetMax(){
        value=a[month.getValue()-1];
    }
    //效验数据合法性
    public boolean validate(){
        if(this.getMonth().getYear().isLeapYear())
            a[1]=29;
        if(value>=1&&value<=a[month.getValue()-1])
            return true;
        else
            return false;
    }
    //日期加一
    public void dayIncrement() {
        value=value+1;
    }
    //日期减一
    public void dayReduction() {
        value=value-1;
    }
}

输入/输出结果

1.
3 2014 2 14 2020 6 14
2312

2.
2 1935 2 17 125340
1591-12-17

3.
1 1999 3 28 6543
2017-2-24

4.
0 2000 5 12 30
Wrong Format

 

对于本题的编写思路:先编写出年月日的类,对输入的数据先进行判断,看是否符合条件。

在编写的过程中要注意对当前输入时间的一个判断,因为应用程序共测试三个功能如:求下n天,求前n天,求两个日期相差的天数。同时输出也有三种year month day n //测试输入日期的下n天,year month day n //测试输入日期的前n天

year1 month1 day1 year2 month2 day2 //测试两个日期之间相差的天数。

题目集四  程序7-3

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int inType;
        Scanner scanner=new Scanner(System.in);
        inType=scanner.nextInt();
        switch(inType)
        {
            case 1:
                double r=scanner.nextDouble();
                if(r<0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Circle circle=new Circle();
                    circle.setRadius(r);
                    System.out.printf("Circle's area:%.2f%n",circle.getArea());
                }
                break;

            case 2:
                double width=scanner.nextDouble();
                double length=scanner.nextDouble();
                if(width<0.0||length<0.0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Rectangle rectangle=new Rectangle();
                    rectangle.setLength(length);
                    rectangle.setWidth(width);
                    System.out.printf("Rectangle's area:%.2f%n",rectangle.getArea());
                }
                break;

            case 3:
                double R=scanner.nextDouble();
                if(R<0.0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Ball ball=new Ball();
                    ball.setRadius(R);
                    System.out.printf("Ball's surface area:%.2f%n",ball.getArea());
                    System.out.printf("Ball's volume:%.2f%n",ball.getVolume());
                }
                break;

            case 4:
                double Width=scanner.nextDouble();
                double Length=scanner.nextDouble();
                double height=scanner.nextDouble();
                if(Width<0.0||Length<0.0||height<0.0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Box box=new Box();
                    box.setHeight(height);
                    box.setWidth(Width);
                    box.setLength(Length);
                    System.out.printf("Box's surface area:%.2f%n",box.getArea());
                    System.out.printf("Box's volume:%.2f%n",box.getVolume());
                }
                break;

            default:
                System.out.print("Wrong Format");
        }
    }
}

class Shape //定义一个无自身属性,有一个返回值为0.0的求面积方法
{
    public Shape()
    {
        System.out.println("Constructing Shape");
    }
}

class Circle extends Shape//继承自Shape
{
    public Circle()
    {
        System.out.println("Constructing Circle");
    }
    private double radius;//新定义一个半径

    public void setRadius(double radius) {// 设置半径
        this.radius = radius;
    }

    public double getRadius() {// 获取半径
        return radius;
    }

    public double getArea() {
        // TODO Auto-generated method stub
        return Math.PI *radius*radius;//重写父类的方法
    }

}

class Rectangle extends Shape
{
    public Rectangle()
    {
        System.out.println("Constructing Rectangle");
    }
    private double width;
    private double length;
    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public double getArea() {
        // TODO Auto-generated method stub
        return width*length;
    }

}

class Ball extends Circle
{
    public Ball()
    {
        System.out.println("Constructing Ball");
    }

    public double getArea() {
        // TODO Auto-generated method stub
        return 4*super.getArea();//方法的重载,super关键字
    }

    public double getVolume()
    {
        double R=getRadius();
        return 4.0/3.0*R*R*R* Math.PI;
    }

}

class Box extends Rectangle
{
    public Box()
    {
        System.out.println("Constructing Box");
    }

    private double height;

    public void setHeight(double height) {
        this.height = height;
    }
    public double getVolume()
    {
        return height*super.getArea();
    }

    public double getArea() {
        // TODO Auto-generated method stub
        double W=getWidth();
        double L=getLength();
        return 2*(W*L+W*height+L*height);
    }
}

输入/输出结果

1.
1 1.0
Constructing Shape
Constructing Circle
Circle's area:3.14

2.
4 3.6 2.1 0.01211
Constructing Shape
Constructing Rectangle
Constructing Box
Box's surface area:15.26
Box's volume:0.09

3.
2 -2.3 5.110
Wrong Format

对于本题的编写思路:先判断输入的是什么,再调用相应函数计算得出结果,对于不正确的输入要在判断后输出“结果错误”。

本题在程序编写上没有什么特别需要注意的地方,主要是需要注意图形继承类的编写方法。

题目集五  程序7-4

//测试点并没有全部通过!!!
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Scanner x = new Scanner(System.in);
        StringBuilder a = new StringBuilder();
        Map map=new TreeMap();
        String[] gjc = {"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while"};
        String kg,exit="exit";
        int i,n,flag=0;

        //输入
        kg = x.nextLine();
        while( !kg.equals(exit)) {
            a.append(kg.replaceAll("//.*", " ").replaceAll("\".*\"", " "));//去掉"//"后和的内容以及双引号里的内容
            kg = x.nextLine();
            flag=1;
        }
        String b = a.toString().replaceAll("/\\*\\s*.*\\s*\\*/", " ");//去掉"/* */"里的内容,放入字符串b中
        //System.out.println(b);

        //如果没有内容
        if(flag==0) {
            System.out.println("Wrong Format");
        }

        // 循环找每个关键词出现的次数
        for(i=0;i< gjc.length;i++) {
            Pattern pattern = Pattern.compile("\\b"+gjc[i]+"\\b");//创建关键词的正则表达式
            Matcher matcher = pattern.matcher(b);//字符串与关键词匹配
            n=0;
            while(matcher.find()) {//找到该关键词的话,记录该关键词的次数
                n++;
                //System.out.println(matcher.group());

            }
            if(n!=0){//把次数不是0的关键词替换为次数
                map.put(gjc[i], n);
            }
            //System.out.println(map);
        }
        //System.out.println(map);
        String map1= String.valueOf(map);//把map转化为字符串map1
        //System.out.println(map1);
        String map2=map1.replace("{","").replace("}","");//把map1里的"{""}"去掉存入字符串map2
        //System.out.println(map2);
        String[] map3=map2.split(", ");//把map2根据", "分开,存入字符串数组map3

        //循环输出
        for (i=0;i< map3.length;i++){
            String[] map4=map3[i].split("=");//把每个字符串map3根据"="分开,存入字符串数组map4
            System.out.println(map4[1]+"\t"+map4[0]);
        }

    }
}

输入/输出结果

输入:
//Test public method
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
exit

输出:
1    float
3    if
2    int
2    new
2    public
3    this
2    throw

本题在编写的时候遇到了不少的问题,我本人基本是通过向同学请教完成的,因此在编写过程的注意事项上要提醒各位首先要注意输出结果是按统计出的关键字及数量按照关键字升序进行排序输出,所以一定要注意这些细节。

题目集六  程序7-1

import java.util.Scanner;

public class Main {
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        String qq = input.nextLine();
        if(qq.matches("[1-9][\\d]{4,14}"))
        {
            System.out.println("你输入的QQ号验证成功");
        }
        else
        {
            System.out.println("你输入的QQ号验证失败");
        }
    }
}

输入/输出结果

1.
1234567890
你输入的QQ号验证成功

2.
123456789O
你输入的QQ号验证失败

 

7-3

import java.util.Scanner;

public class Main {
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        String jym = input.nextLine();
        if(jym.matches("[\\d||\\w]{1,4}"))
        {
            System.out.println(jym+"属于验证码");
        }
        else
        {
            System.out.println(jym+"不属于验证码");
        }
    }
}

输入/输出结果

1.
123A
123A属于验证码

2.
12?AD
12?AD不属于验证码

 

7-4

import java.util.Scanner;

public class Main {
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        String sno = input.nextLine();
        if(sno.matches("2020([1][1-7]|61|[7][123]|[8][12])([0][1-9]|[1][1-9]|[2][1-9]|[3][1-9]|[4][0])"))
        {
            System.out.println("正确");
        }
        else
        {
            System.out.println("错误");
        }
    }
}

输入/输出结果

1.
20201536
正确

2.
20201541
错误

对于这三道正则表达式的题来说只需要弄清正则表达式的编写方式,将输入的数据进行判断即可得出结果,总体而言算是这三次大作业中比较简单的题型。

但是在程序编写时仍然要注意正则表达式的规范书写。

7-5

import java.util.Scanner;
import java.util.Arrays;


//Shape类
abstract class Shape{
    public abstract double Mj();
}
//Circle类
class Circle extends Shape{
    private double r;
    public Circle(double r){
        super();
        this.r=r;
    }
    //getter
    public double getR(){
        return r;
    }
    //setter
    public void setR(double r){
        this.r = r;
    }

    public double Mj(){//计算圆面积
        return Math.PI*r*r;
    }
}
//Rectangle类
class Rectangle extends Shape{
    private double a,b;
    public Rectangle(double a, double b){
        super();
        this.a=a;
        this.b=b;
    }
    //getter
    public double A(){
        return a;
    }
    public double B(){
        return b;
    }
    //setter
    public void setA(double a){
        this.a=a;
    }
    public void setB(double b){
        this.b=b;
    }

    public double Mj(){//计算矩形面积
        return a*b;
    }
}
//Triangle类
class Triangle extends Shape{
    private double a;
    private double b;
    private double c;
    public Triangle(double a, double b, double c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    //getter
    public double A(){
        return a;
    }
    public double B(){
        return b;
    }
    public double C(){
        return c;
    }
    //setter
    public void setA(double a){
        this.a=a;
    }
    public void setB(double b){
        this.b=b;
    }
    public void setC(double c){
        this.c=c;
    }
    public double Mj(){//计算三角形面积
        double s1,s2;
        s1=(a+b+c)/2;
        s2=Math.sqrt(s1*(s1-a)*(s1-b)*(s1-c));
        return s2;
    }
}
//主类
public class Main{
    public static void main(String[] args){
        Scanner x = new Scanner(System.in);
        int q,w,e,gs=0,h;//个数
        q=x.nextInt();w=x.nextInt();e=x.nextInt();
        h=q+w+e;
        double[] he=new double [q+w+e];
        double zh=0;
        int i,flag=0;
        Shape []c=new Circle[q];
        Shape []r=new Rectangle[w];
        Shape []t=new Triangle[e];

        for(i=0;i<q;i++){//三角形
            double bj;
            bj=x.nextDouble();//输入半径
            if(bj<=0){//判断是否合法
                flag=1;
            }
            c[i]=new Circle(bj);//把半径传入Circle类
            zh=zh+c[i].Mj();//计算总面积
            he[gs]=c[i].Mj();//把面积传入数组he
            gs++;
        }

        for(i=0;i<w;i++){//矩形
            double db;
            double cb;
            db=x.nextDouble();cb=x.nextDouble();//输入边长
            if(db<0||cb<0){//判断是否合法
                flag=1;
            }
            r[i]=new Rectangle(db,cb);//把边长传入Rectangle类
            zh=zh+r[i].Mj();//计算总面积
            he[gs]=r[i].Mj();//把面积传入数组he
            gs++;

        }

        for(i=0;i<e;i++){//三角形
            double a;
            double b;
            double d;
            double[] three=new double[3];
            three[0]=x.nextDouble();three[1]=x.nextDouble();three[2]=x.nextDouble();//输入边长
            Arrays.sort(three);//三边从小到大排序
            a=three[0];b=three[1];d=three[2];
            if(a<0||b<0||d<0||a+b<=d){//判断是否合法
                flag=1;
            }
            t[i]=new Triangle(a,b,d);//把边长传入Triangle类
            zh=zh+t[i].Mj();//计算总面积
            he[gs]=t[i].Mj();//把面积传入数组he
            gs++;
        }

        System.out.println("Original area:");
        for (i=0;i<h;i++){
            System.out.printf("%.2f ",he[i]);
        }
        System.out.printf("\nSum of area:%.2f\n",zh);
        System.out.println("Sorted area:");
        Arrays.sort(he);
        for(i=0;i<h;i++){
            System.out.printf("%.2f ",he[i]);
        }
        System.out.printf("\nSum of area:%.2f",zh);
    }
}

输入/输出结果

1.
1 1 1 2.3 3.2 3.2 6.5 3.2 4.2

Original area:
16.62 10.24 5.68 
Sum of area:32.54
Sorted area:
5.68 10.24 16.62 
Sum of area:32.54

2.
0 2 2 2.3 2.5 56.4 86.5 64.3 85.6 74.6544 3.2 6.1 4.5

Original area:
5.75 4878.60 2325.19 7.00 
Sum of area:7216.54
Sorted area:
5.75 7.00 2325.19 4878.60 
Sum of area:7216.54

3.
0 0 1 3 3 6

Wrong Format

对于本题的编写思路:首先,本题与题目集4中的图形继承题有着一定的相似之处,因此我们可以借用之前的一些编写方法来降低本题的编写难度。对于本题而言要先判断输入的是一个什么样的图形,然后根据程序中相应的函数进行计算并得出结果。

本题编写的困难之处在于能否判断出输入的是否是非法值,能否判断出输入的是哪一种图形,再去找到相应算法。

7-6

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int inType;
        Scanner scanner=new Scanner(System.in);
        inType=scanner.nextInt();
        switch(inType)
        {
            case 1:
                double r=scanner.nextDouble();
                if(r<0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Circle circle=new Circle();
                    circle.setRadius(r);
                    System.out.printf("Circle's area:%.2f%n",circle.getArea());
                }
                break;

            case 2:
                double width=scanner.nextDouble();
                double length=scanner.nextDouble();
                if(width<0.0||length<0.0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Rectangle rectangle=new Rectangle();
                    rectangle.setLength(length);
                    rectangle.setWidth(width);
                    System.out.printf("Rectangle's area:%.2f%n",rectangle.getArea());
                }
                break;

            case 3:
                double R=scanner.nextDouble();
                if(R<0.0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Ball ball=new Ball();
                    ball.setRadius(R);
                    System.out.printf("Ball's surface area:%.2f%n",ball.getArea());
                    System.out.printf("Ball's volume:%.2f%n",ball.getVolume());
                }
                break;

            case 4:
                double Width=scanner.nextDouble();
                double Length=scanner.nextDouble();
                double height=scanner.nextDouble();
                if(Width<0.0||Length<0.0||height<0.0) {
                    System.out.println("Wrong Format");
                }
                else {
                    Box box=new Box();
                    box.setHeight(height);
                    box.setWidth(Width);
                    box.setLength(Length);
                    System.out.printf("Box's surface area:%.2f%n",box.getArea());
                    System.out.printf("Box's volume:%.2f%n",box.getVolume());
                }
                break;

            default:
                System.out.print("Wrong Format");
        }
    }
}

class Shape //定义一个无自身属性,有一个返回值为0.0的求面积方法
{
    public Shape()
    {
        System.out.println("Constructing Shape");
    }
}

class Circle extends Shape//继承自Shape
{
    public Circle()
    {
        System.out.println("Constructing Circle");
    }
    private double radius;//新定义一个半径

    public void setRadius(double radius) {// 设置半径
        this.radius = radius;
    }

    public double getRadius() {// 获取半径
        return radius;
    }

    public double getArea() {
        // TODO Auto-generated method stub
        return Math.PI *radius*radius;//重写父类的方法
    }

}

class Rectangle extends Shape
{
    public Rectangle()
    {
        System.out.println("Constructing Rectangle");
    }
    private double width;
    private double length;
    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public double getArea() {
        // TODO Auto-generated method stub
        return width*length;
    }

}

class Ball extends Circle
{
    public Ball()
    {
        System.out.println("Constructing Ball");
    }

    public double getArea() {
        // TODO Auto-generated method stub
        return 4*super.getArea();//方法的重载,super关键字
    }

    public double getVolume()
    {
        double R=getRadius();
        return 4.0/3.0*R*R*R* Math.PI;
    }

}

class Box extends Rectangle
{
    public Box()
    {
        System.out.println("Constructing Box");
    }

    private double height;

    public void setHeight(double height) {
        this.height = height;
    }
    public double getVolume()
    {
        return height*super.getArea();
    }

    public double getArea() {
        // TODO Auto-generated method stub
        double W=getWidth();
        double L=getLength();
        return 2*(W*L+W*height+L*height);
    }
}

输入/输出结果

1.
2 3.6 2.45

12.57
8.82

2.
9 0.5 -7.03

Wrong Format

其中:

  1.GetArea为一个接口,无属性,只有一个GetArea(求面积)的抽象方法;

  2.Circle及Rectangle分别为圆类及矩形类,分别实现GetArea接口 

  3.要求:在Main类的主方法中分别定义一个圆类对象及矩形类对象(其属性值由键盘输入),使用接口的引用分别调用圆类对象及矩形类对象的求面积的方法,直接输出两个图形的面积值。(要求只保留两位小数)

本题值得注意的一点是必须要实现类的封装性、继承性和多态性。

三、心得总结

Java是一种面向对象的语言,相比于c语言的编写来说,在编写代码前的思考更为重要,同时要注意java是面向对象的语言,要用面向对象的思维进行思考。将Java学习的思维方式更好地运用,才能越走越远。
通过这三次的大作业,我认识到了很多的问题与不足,我对java这门课程的学习还存在很多的问题,我相信在今后的学习中课程只会越来越难,如果没有花费足够的到java的学习当中去仅靠老师上课所传授的知识,是不可能够独立完成老师所布置的人物的,所以一定要利用课余的时间进行学习,否则与同学的差距只会越来越大。在今后的学习中,不能只靠老师所传授的知识,一定要在课外进行自我学习,才能越走越远,越变越强!

posted on 2021-11-12 21:01  Rajay_Liu  阅读(32)  评论(0编辑  收藏  举报

导航