PTA总结性Blog

一、前言

   首先对这几次题目的知识点、题量、难度进行总结。在PTA六、七、八三次作业主要是围绕电信计费系统的作业。从一开始的座机计费,再到手机+座机计费,最后到短信计费。其中第七次作业是难度最大的一次题目,因为它综合考虑的因素最多,需要花一定的时间才能解决至于其它的题目,C~K的班级、阅读程序,按照题目需求修改程序、商品内部类购物券、动物发声模拟器这几道题目都不是难度非常大的题目,只要认真审题就可以解决。

二、设计与分析

   1)pta第六次作业7-2

 

定义容器Container接口。模拟实现一个容器类层次结构,并进行接口的实现、抽象方法重写和多态机制测试。各容器类实现求表面积、体积的方法。

 

  1. 定义接口Container:
    属性:
    public static final double pi=3.1415926;
    抽象方法:
    public abstract double area();
    public abstract double volume();
    static double sumofArea(Container c[]);
    static double sumofVolume(Container c[]);
    其中两个静态方法分别计算返回容器数组中所有对象的面积之和、周长之和;
  2. 定义Cube类、Cylinder类均实现自Container接口。
    Cube类(属性:边长double类型)、Cylinder类(属性:底圆半径、高,double类型)。

 

输入格式:

 

第一行n表示对象个数,对象类型用cube、cylinder区分,cube表示立方体对象,后面输入边长,输入cylinder表示圆柱体对象,后面是底圆半径、高。

 

输出格式:

 

分别输出所有容器对象的表面积之和、体积之和,结果保留小数点后2位。

代码如下:

import java.util.Scanner;
import java.util.Stack;

public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int i = in.nextInt();
        String str = new String();
        Cube a[] = new Cube[i];
        Cylinder b[] = new Cylinder[i];

        int x= 0,y=0;
        for(int j = 0 ;j < i; j++){
              str = in.next();
              if(str.equalsIgnoreCase("Cube"))
              {
                  double l = in.nextDouble();
                  a[x] = new Cube(l);
                  x++;
              }
              else
              {
                  double r = in.nextDouble();
                  double h = in.nextDouble();
                  b[y] = new Cylinder(r,h);
                  y++;
              }
        }
        double S = 0;
        double V = 0;
        S = Container.sumArea(a) + Container.sumArea(b);
        V = Container.sumVolume(a)+Container.sumVolume(b);
        System.out.printf("%.2f\n",S);
        System.out.printf("%.2f",V);

    }
}
class  Cube implements Container{
double l;
public Cube(double l){
    this.l = l;
}

public double area(){
    double area = 6*l*l;
    return area;
}

public double volume(){
    double volume = l*l*l;
    return volume;
}
}
class Cylinder implements Container
{
    double r,h;
    double pi = 3.1415926;
    public Cylinder(double r, double h) {
        this.r = r;
        this.h = h;
    }
    public double area()
    {
        double area = 2*pi*r*r+2*pi*r*h;
        return area;
    }
    public double volume(){
        double volume = pi*r*r*h;
        return volume;
    }

}
interface Container{
    double area();
    double volume();
    static double sumArea(Container c[]){
        double S = 0;
        int i = 0;
        while(c[i]!=null)
        {
            S = S + c[i].area();
            i++;
        }
        return S ;
    }
    static  double sumVolume(Container c[]){
        double V = 0;
        int i = 0;
        while (c[i] !=null ){
            V = V + c[i].volume();
            i++;
        }
        return V ;
    }
}

这道题目还是比较简单的。

2)pta第七次作业

①、

7-2 sdut-Collection-sort--C~K的班级(II)
 

经过不懈的努力,C~K终于当上了班主任。

现在他要统计班里学生的名单,但是C~K在教务系统中导出班级名单时出了问题,发现会有同学的信息重复,现在他想把重复的同学信息删掉,只保留一个,
但是工作量太大了,所以找到了会编程的你,你能帮他解决这个问题吗?

输入格式:

第一行输入一个N,代表C~K导出的名单共有N行(N<100000).

接下来的N行,每一行包括一个同学的信息,学号 姓名 年龄 性别。

输出格式:

第一行输出一个n,代表删除重复名字后C~K的班级共有几人。

接下来的n行,输出每一个同学的信息,输出按照学号从小到大的顺序。

代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        HashSet<Student> students = new HashSet<>();
        int in = input.nextInt();
        for (int i = 0; i < in; i++) {
            students.add(new Student(input.next(), input.next(), input.next(), input.next()));
        }
        System.out.println(students.size());
        ArrayList<Student> studentArrayList = new ArrayList<>(students);
        Collections.sort(studentArrayList);
        for (Student student : studentArrayList) System.out.println(student);
    }
}
class Student implements Comparable<Student>{
    String ID, name, age, sex;

    public Student(String ID, String name, String age, String sex) {
        this.ID = ID;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    
    public boolean equals(Object obj) {
        return ID.equals(((Student) obj).ID);
    }
    
    public String toString() {
        return ID + " " + name + " " + age + " " + sex;
    }
    
    public int compareTo(Student o) {
        return Integer.compare(Integer.parseInt(ID), Integer.parseInt(o.ID));
    }
    
    public int hashCode() {
        return Integer.parseInt(ID);
    }
}

②、

7-3 阅读程序,按照题目需求修改程序
功能需求:
      使用集合存储3个员工的信息(有序);
      通过迭代器依次找出所有的员工。
 

提示:学生复制以下代码到编程区,并按需求进行调试修改。


// 1、导入相关包

//定义员工类
class Employee {

	private String name;
	private int age;

	public Employee() {
		super();
	}

	public Employee(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

//主函数
public class Main {

	public static void main(String[] args) {
				// 1、创建有序集合对象
				Collection c ;

      // 创建3个员工元素对象
		for (int i = 0; i < 3; i++) {
			Scanner sc = new Scanner(System.in);
			String employeeName = sc.nextLine();
			int employeeAge = sc.nextInt();
			
			Employee employee = new Employee(employeeName, employeeAge);
			c.add(employee);
		}			
				
				
				
				// 2、创建迭代器遍历集合
				Iterator it;
				
				//3、遍历
				while (it.hasnext) {
					
					//4、集合中对象未知,向下转型
					Employee e =  it.next();
					
					System.out.println(e.getName() + "---" + e.getAge());
				}
	}

}代码:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;

//定义员工类
class Employee {

    private String name;
    private int age;

    public Employee() {
        super();
    }

    public Employee(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

//主函数
public class Main {

    public static void main(String[] args) {
        // 1、创建有序集合对象
        Collection<Employee> c = new ArrayList<>();
        

        // 创建3个员工元素对象
        for (int i = 0; i < 3; i++) {
            Scanner sc = new Scanner(System.in);
            String employeeName = sc.nextLine();
            int employeeAge = Integer.parseInt(sc.nextLine());

            Employee employee = new Employee(employeeName, employeeAge);
            c.add(employee);
        }

        // 2、创建迭代器遍历集合
        Iterator<Employee> it = c.iterator();

        //3、遍历
        while (it.hasNext()) {
            //4、集合中对象未知,向下转型
            Employee e = it.next();

            System.out.println(e.getName() + "—" + e.getAge());
        }
    }

}
3)pta第八次作业
①、
7-2 编写一个类Shop(商店)、内部类InnerCoupons(内部购物券)

编写一个类Shop(商店),该类中有一个成员内部类InnerCoupons(内部购物券),可以用于购买该商店的牛奶(假设每箱牛奶售价为50元)。要求如下:
(1)Shop类中有私有属性milkCount(牛奶的箱数,int类型)、公有的成员方法setMilkCount( )getMilkCount( )分别用于设置和获取牛奶的箱数。
(2)成员内部类InnerCoupons,有公有属性value(面值,int类型),一个带参数的构造方法可以设定购物券的面值value,一个公有的成员方法buy( )要求输出使用了面值为多少的购物券进行支付,同时使商店牛奶的箱数减少value/50。
(3)Shop类中还有成员变量coupons50(面值为50元的内部购物券,类型为InnerCoupons)、coupons100(面值为100元的内部购物券,类型为InnerCoupons)。
(4)在Shop类的构造方法中,调用内部类InnerCoupons的带参数的构造方法分别创建上面的购物券coupons50、coupons100。


在测试类Main中,创建一个Shop类的对象myshop,从键盘输入一个整数(大于或等于3),将其设置为牛奶的箱数。假定有顾客分别使用了该商店面值为50的购物券、面值为100的购物券各消费一次,分别输出消费后商店剩下的牛奶箱数。

输入格式:

输入一个大于或等于3的整数。

输出格式:

使用了面值为50的购物券进行支付
牛奶还剩XX箱
使用了面值为100的购物券进行支付
牛奶还剩XX箱

import java.util.Scanner;

public class Main {
    public static <Shop> void main(String[] args) {
        shop myshop = new shop();
        Scanner  in = new Scanner(System.in);
        myshop.setMilkCount(in.nextInt());
        System.out.println("使用了面值为50的购物券进行支付");
        myshop.coupons50.buy();
        System.out.println("使用了面值为100的购物券进行支付");
        myshop.coupons100.buy();
    }
}
class shop{
    private int milkCount;
    InnerCoupons coupons50 = new InnerCoupons(50);
    InnerCoupons coupons100 = new InnerCoupons(100);
    public  void setMilkCount(int k)
    {
        milkCount = k;
    }
    public int  getMilkCount(){
        return milkCount;
    }
    public class InnerCoupons{
        public int value;
        InnerCoupons(int value)
        {
            this.value = value;
        }
        public void buy()
        {
            milkCount = milkCount - value/50;
            System.out.println("牛奶还剩"+milkCount+"箱");
        }

    }
}

②、

7-3 动物发声模拟器(多态)

设计一个动物发生模拟器,用于模拟不同动物的叫声。比如狮吼、虎啸、狗旺旺、猫喵喵……。
定义抽象类Animal,包含两个抽象方法:获取动物类别getAnimalClass()、动物叫shout();
然后基于抽象类Animal定义狗类Dog、猫类Cat和山羊Goat,用getAnimalClass()方法返回不同的动物类别(比如猫,狗,山羊),用shout()方法分别输出不同的叫声(比如喵喵、汪汪、咩咩)。
最后编写AnimalShoutTest类测试,输出:
猫的叫声:喵喵
狗的叫声:汪汪
山羊的叫声:咩咩

其中,在AnimalShoutTestMain类中,用speak(Animal animal){}方法输出动物animal的叫声,在main()方法中调用speak()方法,分别输出猫、狗和山羊对象的叫声。

//动物发生模拟器.  请在下面的【】处添加代码。
public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat();
        Dog dog = new Dog();
        Goat goat = new Goat();
        speak(cat);
        speak(dog);
        speak(goat);
    }
    //定义静态方法speak()
         public  static void speak(Animal animal){
        System.out.println(animal.getAnimalClass()+"的叫声:"+animal.shout());
    }

}

//定义抽象类Animal
abstract  class Animal{
    abstract String getAnimalClass();
    abstract String shout();

}
//基于Animal类,定义猫类Cat,并重写两个抽象方法
class Cat extends Animal{
    String getAnimalClass() {
        return "猫";
    }

    String shout() {
        return "喵喵";
    }

        }
//基于Animal类,定义狗类Dog,并重写两个抽象方法
class Dog extends Animal{
    String getAnimalClass() {
        return "狗";
    }

    String shout() {
        return "汪汪";
    }

        }
//基于Animal类,定义山羊类Goat,并重写两个抽象方法
class Goat extends Animal {
    String getAnimalClass() {
        return "山羊";
    }

    String shout() {
        return "咩咩";
    }

        }

电信计费第一次:

 

 

 

 

 

这道题目对我来说还是有挺大的难度的,最后也没有拿到很高的分数,代码如下,还是有很多的地方还需要改进鹤完善
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;

public class Main {

    public  static  void main (String [] args)
    {
        Scanner in = new Scanner(System.in);
        DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        ArrayList<User>users = new ArrayList<>();
        String s;

        while(true)
        {
            s = in.nextLine();

                if(s.charAt(0) != 'u')break;
                else {
                    String [] ss = s.split(" ");
                    String phoneNumber = ss[0].substring(2);
                    User user = new User(phoneNumber);
                    user.setChargeMode(new LandlinePhoneCharging());
                    users.add(user);
                }
            
        }
        Arrays.sort(new ArrayList[]{users});
        s = s.substring(2);
        String [] ss = s.split(" ");
        String startTime;
        String endTime;
        Date StartTime,EndTime;
        for(User user : users)
        {
            if(user.getNumber().equals(ss[0]))
            {
                String call = ss[0].substring(0, 4);
                String  receive = ss[1].substring(0, 4);
                startTime = ss[2] + " " + ss[3];
                endTime = ss[4] + " " + ss[5];
                //Date startTime, Date endTime, String callingAddressAreaCode, String answerAddressAreaCode
                try {
                    StartTime = dateFormat.parse(startTime);
                } catch (ParseException e) {
                    continue;
                }
                try {
                    EndTime = dateFormat.parse(endTime);
                } catch (ParseException e) {
                    continue;
                }
                // CallRecord callRecord = new CallRecord();
                if(check(receive)== 1)
                {
                    user.getUserRecords().addCallingInCityRecord(new CallRecord(StartTime, EndTime, call, receive));
                }
                else if(check(receive) == 2)user.getUserRecords().addCallingInProvinceRecord(new CallRecord(StartTime, EndTime,call,receive));
                else user.getUserRecords().addCallingInLandRecord(new CallRecord(StartTime, EndTime,call,receive));
            }
        }
        while(true)
        {
            s = in.nextLine();
            if(s.equals("end"))break;
            s = s.substring(2);
            String [] sss = s.split(" ");
            String sstartTime;
            String eendTime;
            Date SStartTime,EEndTime;
            for(User user : users)
            {
                if(user.getNumber().equals(sss[0]))
                {
                    String call = sss[0].substring(0, 4);
                    String  receive = sss[1].substring(0, 4);
                    sstartTime = sss[2] + " " + sss[3];
                    eendTime = sss[4] + " " + sss[5];
                    //Date startTime, Date endTime, String callingAddressAreaCode, String answerAddressAreaCode
                    try {
                        SStartTime = dateFormat.parse(sstartTime);
                    } catch (ParseException e) {
                        continue;
                    }
                    try {
                        EEndTime = dateFormat.parse(eendTime);
                    } catch (ParseException e) {
                        continue;
                    }
                    // CallRecord callRecord = new CallRecord();
                    if(check(receive) == 1)
                    {
                        user.getUserRecords().addCallingInCityRecord(new CallRecord(SStartTime, EEndTime, call, receive));
                    }else if(check(receive) == 2)user.getUserRecords().addCallingInProvinceRecord(new CallRecord(SStartTime, EEndTime,call,receive));
                    else user.getUserRecords().addCallingInLandRecord(new CallRecord(SStartTime, EEndTime,call,receive));
                }
            }
        }
        for(User user : users)
        {
            System.out.printf("%s %.1f %.1f\n",user.getNumber(),user.calCost(),user.calBalance());
        }
        //String time = s.substring(s.length() - )
    }
    public  static  int check(String s)
    {
        if(s.equals("0791"))return 1;
        else if(s.equals("0790") || s.equals("0792") || s.equals("0793") || s.equals("0794")||
                s.equals("0795")|| s.equals("0796") || s.equals("0797")|| s.equals("0798")|| s.equals("0799")|| s.equals("0701"))return 2;
        else return 3;
    }
}

class Error {
    public static void wrongNumberOfPoints(ArrayList ps, int num) {
        if (ps.size() != num) {
            System.out.println("wrong number of points");
            System.exit(0);
        }
    }
    public static void wrongPointFormat(String s) {
        if (!s.matches("[+-]?([1-9]\\d*|0)(\\.\\d+)?,[+-]?([1-9]\\d*|0)(\\.\\d+)?")) {
            System.out.println("Wrong Format");
            System.exit(0);
        }
    }
    public static void wrongChoice(String s) {
        if (!s.matches("[1-5]:.+")) {
            System.out.println("Wrong Format");
            System.exit(0);
        }
    }

}
abstract class CallChargeRule extends  ChargeRule{
    abstract double calCost(ArrayList<CallRecord>callRecords);
}
class CallRecord extends  CommunicationRecord{
    Date startTime;
    Date endTime;
    String callingAddressAreaCode;
    String answerAddressAreaCode;

    public CallRecord(Date startTime, Date endTime, String callingAddressAreaCode, String answerAddressAreaCode) {
        this.startTime = startTime;
        this.endTime = endTime;
        this.callingAddressAreaCode = callingAddressAreaCode;
        this.answerAddressAreaCode = answerAddressAreaCode;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public String getCallingAddressAreaCode() {
        return callingAddressAreaCode;
    }

    public void setCallingAddressAreaCode(String callingAddressAreaCode) {
        this.callingAddressAreaCode = callingAddressAreaCode;
    }

    public String getAnswerAddressAreaCode() {
        return answerAddressAreaCode;
    }

    public void setAnswerAddressAreaCode(String answerAddressAreaCode) {
        this.answerAddressAreaCode = answerAddressAreaCode;
    }
}
class InputData {
    private int choice;;//用户输入的选择项
    private ArrayList<Call> Calls = new ArrayList();//用户输入的点坐标
    public int getChoice() {
        return choice;
    }
    public void setChoice(int choice) {
        this.choice = choice;
    }
    public ArrayList<Call> getPoints() {
        return Calls;
    }
    public void addPoint(Call p) {
        this.Calls.add(p);
    }

}
abstract class ChargeMode {
    ArrayList<ChargeRule> chargeRules = new ArrayList<>();

    public ArrayList<ChargeRule> getChargeRules() {
        return chargeRules;
    }

    public void setChargeRules(ArrayList<ChargeRule> chargeRules) {
        this.chargeRules = chargeRules;
    }
    abstract double calCost(UserRecords userRecords);

    abstract double getMonthlyRent();
}
abstract class ChargeRule {
    abstract double calCost(ArrayList<CallRecord> callRecords);

}
class CommunicationRecord {
    String callingNumber;
    String answerNumber;

    public String getCallingNumber() {
        return callingNumber;
    }

    public void setCallingNumber(String callingNumber) {
        this.callingNumber = callingNumber;
    }

    public String getAnswerNumber() {
        return answerNumber;
    }

    public void setAnswerNumber(String answerNumber) {
        this.answerNumber = answerNumber;
    }
}
class Call {
    public double x;
    public double y;
    public Call() {
    }
    public Call(double x, double y) {
        this.x=x;
        this.y=y;
    }
    public void setX(double x) {
        this.x = x;
    }
    public void setY(double y) {
        this.y = y;
    }
    public double getX() {
        return x;
    }
    public double getY() {
        return y;
    }
    public boolean equals(Call p) {
        boolean b = false;
        if(this.x==p.getX()&&this.y==p.getY()) {
            b=true;
        }
        return b;
    }
}
class LandlinePhoneCharging extends ChargeMode{
    double monthlyRent = 20;
    public LandlinePhoneCharging()
    {
        getChargeRules().add(new LandPhoneCityRule());
        getChargeRules().add(new LandPhoneLandRule());
        getChargeRules().add(new LandPhoneProvinceRule());
    }
    double calCost(UserRecords userRecords) {
        double cost = 0;
        cost = getChargeRules().get(0).calCost(userRecords.getCallingInCityRecords()) +
                getChargeRules().get(1).calCost(userRecords.getCallingInLandRecord()) +
                getChargeRules().get(2).calCost(userRecords.getCallingInProvinceRecord());
        return cost;
    }
    public double getMonthlyRent() {
        return monthlyRent;
    }
}
class LandPhoneCityRule extends CallChargeRule{
    double calCost(ArrayList<CallRecord> callRecords) {
        double cost = 0;
        for(CallRecord land : callRecords)
        {
            double sumTimeMinutes = Math.ceil((double) (land.getEndTime().getTime() -
                    land.getStartTime().getTime()) / 1000.0 / 60.0);
            cost += 0.1 * sumTimeMinutes;
        }
        return cost;
    }
}
class LandPhoneLandRule extends CallChargeRule{
    @Override
    double calCost(ArrayList<CallRecord> callRecords) {
        double cost = 0;
        for(CallRecord land : callRecords)
        {
            double sumTimeMinutes = Math.ceil((double) (land.getEndTime().getTime() -
                    land.getStartTime().getTime()) / 1000.0 / 60.0);
            cost += 0.6 * sumTimeMinutes;
        }
        return cost;
    }
}
class LandPhoneProvinceRule extends CallChargeRule{
    @Override
    double calCost(ArrayList<CallRecord> callRecords) {
        double cost = 0;
        for(CallRecord land : callRecords)
        {
            double sumTimeMinutes = Math.ceil((double) (land.getEndTime().getTime() -
                    land.getStartTime().getTime()) / 1000.0 / 60.0);
            cost += 0.3 * sumTimeMinutes;
        }

        return cost;
    }
}
class MessageRecord extends CommunicationRecord{
    String message ;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
class User {
    private static int shabi;




    public class shabi {

        public int shabi()
        {
            double S1=0, S2=0,S3=0;
            double area = S1 + S2 + S3;
            return 0;
        };

    }
    int a = User.shabi;
    UserRecords userRecords = new UserRecords();
    double balance = 100;
    ChargeMode chargeMode;
    String number;

    public User(String number) {
        this.number = number;
    }

    double calBalance()
    {
        return getBalance() - calCost() - chargeMode.getMonthlyRent();
    }
    double calCost(){
        return chargeMode.calCost(userRecords);
    }

    public UserRecords getUserRecords() {
        return userRecords;
    }

    public void setUserRecords(UserRecords userRecords) {
        this.userRecords = userRecords;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public ChargeMode getChargeMode() {
        return chargeMode;
    }

    public void setChargeMode(ChargeMode chargeMode) {
        this.chargeMode = chargeMode;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}
class Item {
    private String title;
    private int playingTime;
    private boolean gotIt = false;
    private String comment;

    public Item() {

    }
    public Item(String title, int playingTime, boolean gotIt, String comment) {
        super();
        this.title = title;
        this.playingTime = playingTime;
        this.gotIt = gotIt;
        this.comment = comment;
    }
    public void print() {
        System.out.println("item");
    }

}
class UserRecords {
    ArrayList<CallRecord> callingInCityRecords = new ArrayList<CallRecord>();
    ArrayList<CallRecord> callingInProvinceRecords = new ArrayList<CallRecord>();
    ArrayList<CallRecord>callingInLandRecords = new ArrayList<CallRecord>();
    ArrayList<CallRecord>answerInCityRecords = new ArrayList<CallRecord>();
    ArrayList<CallRecord>answerInProvinceRecords = new ArrayList<CallRecord>();
    ArrayList<CallRecord>answerInLandRecords = new ArrayList<CallRecord>();
    ArrayList<MessageRecord>sendMessageRecords = new ArrayList<MessageRecord>();
    ArrayList<MessageRecord>receiveMessageRecords = new ArrayList<MessageRecord>();
    public void addCallingInCityRecord(CallRecord callRecord)
    {
        callingInCityRecords.add(callRecord);
    }
    public void addCallingInProvinceRecord(CallRecord callRecord)
    {
        callingInProvinceRecords.add(callRecord);
    }
    public void addCallingInLandRecord(CallRecord callRecord)
    {
        callingInLandRecords.add(callRecord);
    }
    public void answerInCityRecord(CallRecord callRecord)
    {
        answerInCityRecords.add(callRecord);
    }
    public void answerInProvinceRecord(CallRecord callRecord)
    {
        answerInProvinceRecords.add(callRecord);
    }
    public void answerInLandRecord(CallRecord callRecord)
    {
        answerInLandRecords.add(callRecord);
    }
    public void addSendMessageRecords(MessageRecord sendMessageRecord)
    {
        sendMessageRecords.add(sendMessageRecord);
    }
    public void addReceiveMessageRecords(MessageRecord receiveMessageRecord)
    {
        receiveMessageRecords.add(receiveMessageRecord);
    }
    public ArrayList<CallRecord> getCallingInCityRecords() {
        return callingInCityRecords;
    }

    public ArrayList<CallRecord> getCallingInProvinceRecord() {
        return callingInProvinceRecords;
    }

    public ArrayList<CallRecord> getCallingInLandRecord() {
        return callingInLandRecords;
    }

    public ArrayList<CallRecord> getAnswerInCityRecords() {
        return answerInCityRecords;
    }

    public ArrayList<CallRecord> getAnswerInProvinceRecords() {
        return answerInProvinceRecords;
    }

    public ArrayList<CallRecord> getAnswerInLandRecords() {
        return answerInLandRecords;
    }

    public ArrayList<MessageRecord> getSendMessageRecord() {
        return sendMessageRecords;
    }

    public ArrayList<MessageRecord> getReceiveMessageRecord() {return receiveMessageRecords;}
}

 

电信计费第二次:

第二次主要是实现手机+座机计费的一个计费方式,同时针对座机以及手机用户具有不同的计费方式如下。

 

 题目要求:

 

 

 

由于第一次的题目没有做的很好导致第二次的作业也不是很好。
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Main {


    public static void main(String[] args) {
        VendingMachine VM = new VendingMachine();
        Scanner in = new Scanner(System.in);
        DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        ArrayList<User> users = new ArrayList<>();
        String [] s = new String[100];
        int i = VM.main0();
        while(true)
        {
            s[i] = in.nextLine();
            if(s[i].equals("end"))break;
            i ++;
        }
        for(int j = 0;j < i;j ++)
        {
            if(s[j].charAt(0) == 'u')
            {
                //VendingMachine VM = new VendingMachine();
                //if (s[j].equals("")) continue;
                if (checkFirst(s[j]) == false) continue;
                String[] ss = s[j].split("u-");
                String[] sa = ss[VM.main()].split(" ");
                String phoneNumber = sa[0];
                boolean f = false;
                for (User user : users)
                    if (user.getNumber().equals(phoneNumber)) {
                        f = true;
                        break;
                    }
                if (f) continue;
                //System.out.println("1");
                User user = new User(phoneNumber);
                //System.out.println(s[j].charAt(s[j].length() - 1));
                //System.out.println(sa[1]);
                int k = Integer.parseInt(sa[VM.main()]);
                if (k == VM.main0())
                    user.setChargeMode(new LandlinePhoneCharging());
                else
                    user.setChargeMode(new MobilePhoneCharging());
                users.add(user);
            }
        }
        for(int j = 0;j < i;j ++)
        {
            if(s[j].equals(""))continue;
            if(s[j].charAt(0) == 't')
            {
                //VendingMachine VM = new VendingMachine();
                if (checkString(s[j]) == true) {
                    String [] ss = s[j].split("t-");
                    String[] sa = ss[VM.main()].split(" ");
                    String startTime;
                    String endTime;
                    Date StartTime = null, EndTime = null;
                    // boolean haveEfficient = false;
                    for (User user : users) {

                        if (user.getNumber().equals(sa[0])) {
                            // haveEfficient = true;
                            if (sa.length == 6) {
                                String call = sa[0].substring(0, 4);
                                String receive = sa[VM.main()].substring(0, 4);
                                startTime = sa[VM.main1()] + " " + sa[3];
                                endTime = sa[4] + " " + sa[5];
                                //Date startTime, Date endTime, String callingAddressAreaCode, String answerAddressAreaCode
                                try {
                                    StartTime = dateFormat.parse(startTime);
                                } catch (ParseException e) {
                                    continue;
                                }
                                try {
                                    EndTime = dateFormat.parse(endTime);
                                } catch (ParseException e) {
                                    continue;
                                }
                                //VendingMachine VM = new VendingMachine();
                                //System.out.println(VM.main());

                                if (checkCode(receive) == VM.main()) {
                                    user.getUserRecords().addCallingInCityRecord(new CallRecord(StartTime, EndTime, call, receive));
                                } else if (checkCode(receive) == VM.main1())
                                    user.getUserRecords().addCallingInProvinceRecord(new CallRecord(StartTime, EndTime, call, receive));
                                else
                                    user.getUserRecords().addCallingInLandRecord(new CallRecord(StartTime, EndTime, call, receive));
                            }
                        }
                    }

                }
            }
        }


        //座机打座机 座机打手机 手机打座机 手机打手机
        TreeMap<String, User> treeMap = new TreeMap<>();
        for (User user : users) {
            treeMap.put(user.getNumber(), user);
        }
        Iterator<User> t = treeMap.values().iterator();
        while (t.hasNext()) {
            User user = t.next();
            System.out.println(user.number + " " + user.calCost() + " " + user.calBalance());
        }
    }
    static boolean checkString(String str) {
        //月份:((((20)\d{2}).(0?[13578]|1[02]).(0?[1-9]|[12]\d|3[01]))|(((19|20)\d{2}).(0?[469]|11).(0?[1-9]|[12]\d|30))|(((19|20)\d{2}).0?2.(0?[1-9]|1\d|2[0-8]))) ([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]
        //座机打座机
        //座机打手机           t-0[0-9]{10,11} 1[0-9]{10} [0-9]{3,4}
        if(str.matches("t-0[0-9]{10,11} 0[0-9]{9,11} ((((20)\\d{2}).(0?[13578]|1[02]).(0?[1-9]|[12]\\d|3[01]))|(((19|20)\\d{2}).(0?[469]|11).(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2}).0?2.(0?[1-9]|1\\d|2[0-8]))) ([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9] ((((20)\\d{2}).(0?[13578]|1[02]).(0?[1-9]|[12]\\d|3[01]))|(((19|20)\\d{2}).(0?[469]|11).(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2}).0?2.(0?[1-9]|1\\d|2[0-8]))) ([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]"))
            return true;


        else
            return false;
    }

    static boolean checkFirst(String s) {
        if(s.matches("u-0[0-9]{10,11} [0-1]"))
            return true;

        return false;
    }



    public static int checkCode(String s) {
        VendingMachine VM = new VendingMachine();
        if (s.equals("0791")) return VM.main();//市内
        else if (s.equals("0790") || s.equals("0792") || s.equals("0793") || s.equals("0794") ||
                s.equals("0795") || s.equals("0796") || s.equals("0797") || s.equals("0798") || s.equals("0799") || s.equals("0701"))
            return VM.main1();//省内
        else return 3;//国内
    }

    public abstract static class ChargeRule {
        abstract double calCost(ArrayList<CallRecord> callRecords);
    }

    public static class MobilePhoneCityCallCityRule extends CallChargeRule {
        @Override
        double calCost(ArrayList<CallRecord> callRecords) {
            double cost = 0;
            for(CallRecord c : callRecords)
            {
                double sumTimeMinutes = Math.ceil((double) (c.getEndTime().getTime() -
                        c.getStartTime().getTime()) / 1000.0 / 60.0);
                cost += 0.1 * sumTimeMinutes;
            }
            return cost;
        }
    }

    public static class MobilePhoneCharging extends  ChargeMode{

        double monthlyRent = 15;
        public MobilePhoneCharging ()
        {
            getChargeRules().add(new MobilePhoneCityCallCityRule());
//            getChargeRules().add(new MobilePhoneCityCallProvinceRule());
            getChargeRules().add(new MobilePhoneCityCallLandRule());
//            getChargeRules().add(new MobilePhoneDomesticRoamingCallRule());
//            getChargeRules().add(new MobilePhoneProvincialRoamingCallRule());
//            getChargeRules().add(new MobilePhoneRoamingAnsweringOutsideProvinceRule());
        }
        @Override
        double calCost(UserRecords userRecords) {
            VendingMachine VM = new VendingMachine();
            double cost = 0;
            cost = getChargeRules().get(0).calCost(userRecords.getMobilePhoneCityCallCity()) +
                    getChargeRules().get(VM.main()).calCost(userRecords.getMobilePhoneCityCallProvince()) +
                    getChargeRules().get(VM.main1()).calCost(userRecords.getMobilePhoneCityCallLand())
                    + getChargeRules().get(3).calCost(userRecords.getMobilePhoneDomesticRoamingCall()) +
                    getChargeRules().get(4).calCost(userRecords.getMobilePhoneProvincialRoamingCall())
                    + getChargeRules().get(5).calCost(userRecords.getMobilePhoneRoamingAnsweringOutsideProvince());
            return cost;
        }
        @Override
        public double getMonthlyRent() {
            return monthlyRent;
        }
    }

    public abstract static class CallChargeRule extends ChargeRule {
        abstract double calCost(ArrayList<CallRecord> callRecords);
    }

//    public static class MobilePhoneProvincialRoamingCallRule extends CallChargeRule {
//
//        @Override
//        double calCost(ArrayList<CallRecord> callRecords) {
//            double cost = 0;
//            for(CallRecord c : callRecords)
//            {
//                double sumTimeMinutes = Math.ceil((double) (c.getEndTime().getTime() -
//                        c.getStartTime().getTime()) / 1000.0 / 60.0);
//                cost += 0.3 * sumTimeMinutes;
//            }
//            return cost;
//        }
//    }

//    public static class MessageRecord extends CommunicationRecord {
//        String message ;
//
//        public String getMessage() {
//            return message;
//        }
//
//        public void setMessage(String message) {
//            this.message = message;
//        }
//    }

    public static class LandlinePhoneCharging extends ChargeMode {
        double monthlyRent = 20;
        public LandlinePhoneCharging()
        {
            getChargeRules().add(new LandPhoneCityRule());
            getChargeRules().add(new LandPhoneLandRule());
            getChargeRules().add(new LandPhoneProvinceRule());
        }

        @Override
        double calCost(UserRecords userRecords) {
            VendingMachine VM = new VendingMachine();
            double cost = 0;
            cost = getChargeRules().get(0).calCost(userRecords.getCallingInCityRecords()) +
                    getChargeRules().get(VM.main()).calCost(userRecords.getCallingInLandRecord()) +
                    getChargeRules().get(VM.main1()).calCost(userRecords.getCallingInProvinceRecord());
            return cost;
        }

        @Override
        public double getMonthlyRent() {
            return monthlyRent;
        }
    }

//    public static class MobilePhoneCityCallProvinceRule extends CallChargeRule {
//        @Override
//        double calCost(ArrayList<CallRecord> callRecords) {
//            double cost = 0;
//            for(CallRecord c : callRecords)
//            {
//                double sumTimeMinutes = Math.ceil((double) (c.getEndTime().getTime() -
//                        c.getStartTime().getTime()) / 1000.0 / 60.0);
//                cost += 0.2 * sumTimeMinutes;
//            }
//            return cost;
//        }
//    }

    public static class CommunicationRecord {
        String callingNumber;
        String answerNumber;

        public String getCallingNumber() {
            return callingNumber;
        }

        public void setCallingNumber(String callingNumber) {
            this.callingNumber = callingNumber;
        }

        public String getAnswerNumber() {
            return answerNumber;
        }

        public void setAnswerNumber(String answerNumber) {
            this.answerNumber = answerNumber;
        }
    }

    public static class LandPhoneLandRule extends CallChargeRule {
        @Override
        double calCost(ArrayList<CallRecord> callRecords) {
            double cost = 0;
            for(CallRecord land : callRecords)
            {
                double sumTimeMinutes = Math.ceil((double) (land.getEndTime().getTime() -
                        land.getStartTime().getTime()) / 1000.0 / 60.0);
                cost += 0.6 * sumTimeMinutes;
            }
            return cost;
        }
    }

    public static class User {
        UserRecords userRecords = new UserRecords();
        double balance = 100;
        ChargeMode chargeMode;
        String number;

        public User(String number) {
            this.number = number;
        }

        double calBalance()
        {
            return getBalance() - calCost() - chargeMode.getMonthlyRent();
        }
        double calCost(){
            return chargeMode.calCost(userRecords);
        }

        public UserRecords getUserRecords() {
            return userRecords;
        }

        public void setUserRecords(UserRecords userRecords) {
            this.userRecords = userRecords;
        }

        public double getBalance() {
            return balance;
        }

        public void setBalance(double balance) {
            this.balance = balance;
        }

        public ChargeMode getChargeMode() {
            return chargeMode;
        }

        public void setChargeMode(ChargeMode chargeMode) {
            this.chargeMode = chargeMode;
        }

        public String getNumber() {
            return number;
        }

        public void setNumber(String number) {
            this.number = number;
        }
    }

    public static class CallRecord extends CommunicationRecord {
        Date startTime;
        Date endTime;
        String callingAddressAreaCode;
        String answerAddressAreaCode;

        public CallRecord(Date startTime, Date endTime, String callingAddressAreaCode, String answerAddressAreaCode) {
            this.startTime = startTime;
            this.endTime = endTime;
            this.callingAddressAreaCode = callingAddressAreaCode;
            this.answerAddressAreaCode = answerAddressAreaCode;
        }

        public Date getStartTime() {
            return startTime;
        }

        public void setStartTime(Date startTime) {
            this.startTime = startTime;
        }

        public Date getEndTime() {
            return endTime;
        }

        public void setEndTime(Date endTime) {
            this.endTime = endTime;
        }

        public String getCallingAddressAreaCode() {
            return callingAddressAreaCode;
        }

        public void setCallingAddressAreaCode(String callingAddressAreaCode) {
            this.callingAddressAreaCode = callingAddressAreaCode;
        }

        public String getAnswerAddressAreaCode() {
            return answerAddressAreaCode;
        }

        public void setAnswerAddressAreaCode(String answerAddressAreaCode) {
            this.answerAddressAreaCode = answerAddressAreaCode;
        }
    }

    public static class MobilePhoneCityCallLandRule extends CallChargeRule {
        @Override
        double calCost(ArrayList<CallRecord> callRecords) {
            double cost = 0;
            for(CallRecord c : callRecords)
            {
                double sumTimeMinutes = Math.ceil((double) (c.getEndTime().getTime() -
                        c.getStartTime().getTime()) / 1000.0 / 60.0);
                cost += 0.3 *  sumTimeMinutes;
            }
            return cost;
        }
    }

    public static class UserRecords {
        ArrayList<CallRecord> callingInCityRecords = new ArrayList<CallRecord>();
        ArrayList<CallRecord> callingInProvinceRecords = new ArrayList<CallRecord>();
        ArrayList<CallRecord>callingInLandRecords = new ArrayList<CallRecord>();
        ArrayList<CallRecord>answerInCityRecords = new ArrayList<CallRecord>();
        ArrayList<CallRecord>answerInProvinceRecords = new ArrayList<CallRecord>();
        ArrayList<CallRecord>answerInLandRecords = new ArrayList<CallRecord>();
//        ArrayList<MessageRecord>sendMessageRecords = new ArrayList<MessageRecord>();
//        ArrayList<MessageRecord>receiveMessageRecords = new ArrayList<MessageRecord>();
        ArrayList<CallRecord> mobilePhoneCityCallCity = new ArrayList<CallRecord>();
        ArrayList<CallRecord> mobilePhoneCityCallProvince = new ArrayList<CallRecord>();
        ArrayList<CallRecord> mobilePhoneCityCallLand = new ArrayList<CallRecord>();
        ArrayList<CallRecord> mobilePhoneDomesticRoamingCall = new ArrayList<CallRecord>();
        ArrayList<CallRecord> mobilePhoneProvincialRoamingCall = new ArrayList<CallRecord>();
        ArrayList<CallRecord> mobilePhoneRoamingAnsweringOutsideProvince = new ArrayList<CallRecord>();
        public void addMobilePhoneCityCallCity(CallRecord callRecord){mobilePhoneCityCallCity.add(callRecord);};
        public void addMobilePhoneCityCallProvince(CallRecord callRecord){mobilePhoneCityCallProvince.add(callRecord);};
        public void addMobilePhoneCityCallLand(CallRecord callRecord){mobilePhoneCityCallLand.add(callRecord);};
        public void addMobilePhoneDomesticRoamingCall(CallRecord callRecord){mobilePhoneDomesticRoamingCall.add(callRecord);};
        public void addMobilePhoneProvincialRoamingCall(CallRecord callRecord){mobilePhoneProvincialRoamingCall.add(callRecord);};
        public void addMobilePhoneRoamingAnsweringOutsideProvince(CallRecord callRecord){mobilePhoneRoamingAnsweringOutsideProvince.add(callRecord);};
        public void addCallingInCityRecord(CallRecord callRecord)
        {
            callingInCityRecords.add(callRecord);
        }
        public void addCallingInProvinceRecord(CallRecord callRecord)
        {
            callingInProvinceRecords.add(callRecord);
        }
        public void addCallingInLandRecord(CallRecord callRecord)
        {
            callingInLandRecords.add(callRecord);
        }
        public void answerInCityRecord(CallRecord callRecord)
        {
            answerInCityRecords.add(callRecord);
        }
        public void answerInProvinceRecord(CallRecord callRecord)
        {
            answerInProvinceRecords.add(callRecord);
        }
        public void answerInLandRecord(CallRecord callRecord)
        {
            answerInLandRecords.add(callRecord);
        }
//        public void addSendMessageRecords(MessageRecord sendMessageRecord)
//        {
//            sendMessageRecords.add(sendMessageRecord);
//        }
//        public void addReceiveMessageRecords(MessageRecord receiveMessageRecord)
//        {
//            receiveMessageRecords.add(receiveMessageRecord);
//        }

        public ArrayList<CallRecord> getMobilePhoneCityCallCity() {
            return mobilePhoneCityCallCity;
        }

        public ArrayList<CallRecord> getMobilePhoneCityCallProvince() {
            return mobilePhoneCityCallProvince;
        }

        public ArrayList<CallRecord> getMobilePhoneCityCallLand() {
            return mobilePhoneCityCallLand;
        }

        public ArrayList<CallRecord> getMobilePhoneDomesticRoamingCall() {
            return mobilePhoneDomesticRoamingCall;
        }

        public ArrayList<CallRecord> getMobilePhoneProvincialRoamingCall() {
            return mobilePhoneProvincialRoamingCall;
        }

        public ArrayList<CallRecord> getMobilePhoneRoamingAnsweringOutsideProvince() {
            return mobilePhoneRoamingAnsweringOutsideProvince;
        }

        public ArrayList<CallRecord> getCallingInCityRecords() {
            return callingInCityRecords;
        }

        public ArrayList<CallRecord> getCallingInProvinceRecord() {
            return callingInProvinceRecords;
        }

        public ArrayList<CallRecord> getCallingInLandRecord() {
            return callingInLandRecords;
        }

        public ArrayList<CallRecord> getAnswerInCityRecords() {
            return answerInCityRecords;
        }

        public ArrayList<CallRecord> getAnswerInProvinceRecords() {
            return answerInProvinceRecords;
        }

        public ArrayList<CallRecord> getAnswerInLandRecords() {
            return answerInLandRecords;
        }

//        public ArrayList<MessageRecord> getSendMessageRecord() {
//            return sendMessageRecords;
//        }
//
//        public ArrayList<MessageRecord> getReceiveMessageRecord() {
//            return receiveMessageRecords;
//        }
    }

    public abstract static class ChargeMode {
        ArrayList<ChargeRule> chargeRules = new ArrayList<>();

        public ArrayList<ChargeRule> getChargeRules() {
            return chargeRules;
        }

        public void setChargeRules(ArrayList<ChargeRule> chargeRules) {
            this.chargeRules = chargeRules;
        }
        abstract double calCost(UserRecords userRecords);

        abstract double getMonthlyRent();
    }

//    public static class MobilePhoneRoamingAnsweringOutsideProvinceRule extends CallChargeRule {
//        @Override
//        double calCost(ArrayList<CallRecord> callRecords) {
//            double cost = 0;
//            for(CallRecord c : callRecords)
//            {
//                double sumTimeMinutes = Math.ceil((double) (c.getEndTime().getTime() -
//                        c.getStartTime().getTime()) / 1000.0 / 60.0);
//                cost += 0.3 * sumTimeMinutes;
//            }
//            return cost;
//        }
//    }

    public static class LandPhoneProvinceRule extends CallChargeRule {
        @Override
        double calCost(ArrayList<CallRecord> callRecords) {
            double cost = 0;
            for(CallRecord land : callRecords)
            {
                double sumTimeMinutes = Math.ceil((double) (land.getEndTime().getTime() -
                        land.getStartTime().getTime()) / 1000.0 / 60.0);
                cost += 0.3 * sumTimeMinutes;
            }
            return cost;
        }
    }

    public static class LandPhoneCityRule extends CallChargeRule {
        @Override
        double calCost(ArrayList<CallRecord> callRecords) {
            double cost = 0;
            for(CallRecord land : callRecords)
            {
                double sumTimeMinutes = Math.ceil((double) (land.getEndTime().getTime() -
                        land.getStartTime().getTime()) / 1000.0 / 60.0);
                cost += 0.1 * sumTimeMinutes;
            }
            return cost;
        }
    }

//    public static class MobilePhoneDomesticRoamingCallRule extends CallChargeRule {
//        @Override
//        double calCost(ArrayList<CallRecord> callRecords) {
//            double cost = 0;
//            for(CallRecord c : callRecords)
//            {
//                double sumTimeMinutes = Math.ceil((double) (c.getEndTime().getTime() -
//                        c.getStartTime().getTime()) / 1000.0 / 60.0);
//                cost += 0.6 * sumTimeMinutes;
//            }
//            return cost;
//        }
//    }
}
class VendingMachine {
    int price = 80;
    int balance;
    int total;

    void setPrice(int price)
    {
        this.price =  price ;
        this.getFood();
    }
    void showPrompt()
    {
        System.out.println("Welcome");
        showBalance();
    }

    void insertMoney(int amount)
    {
        balance =  balance +amount;
    }

    void showBalance()
    {
        System.out.println(this.balance);
    }

    void getFood()
    {
        if(balance >= price )
        {
            System.out.println("Here you are.");
            balance = balance - price ;
            total = total + price;
        }

    }
    public int main()
    {
        return 1;
    }
    public int main1()
    {
        return 2;
    }
public int main0()
{
    return 0;
}



}

电信计费第三次:

第三次的电信计费相较于前面两次的题目容易了不少,只需要实现短信计费的功能,相较于前面两次的还是比较简单的的题目了。

 

 

 

代码如下:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        MessageRecord messageRecord = new MessageRecord();
        Scanner in = new Scanner(System.in);
        ArrayList<User> users = new ArrayList<>();
        String [] s = new String[100];
        VendingMachine VM  = new VendingMachine();
        int zero = VM.insertMoney();

        int i = zero;
        while(true)
        {
            s[i] = in.nextLine();
            if(s[i].equals("end"))break;
            i ++;
        }
        int two = VM.showBalance();
        int one = VM.showPrompt();
        for(int j = zero;j < one;j ++)
        {
            if(s[j].charAt(zero) == 'u')
            {
                if (checku(s[j]) == false) continue;
                String[] ss = s[j].split("u-");
                String[] sa = ss[1].split(" ");
                String phoneNumber = sa[zero];
                boolean f = false;
                for (User user : users)
                   if (user.getNumber().equals(phoneNumber)) {
                       f = true;
                       break;
                   }
                if (f) continue;
                User user = new User(phoneNumber);
                users.add(user);
            }
        }
        for(int j = 0;j < i;j ++)
        {

            if(s[j].equals(""))continue;
            if(s[j].charAt(zero) == 'm') {
                if (checkm(s[j])) {
                    String[] num = s[j].split("m-");
                    String[] num1 = num[one].split(" ");
                    for (User user : users) {
                        if (user.getNumber().equals(num1[zero])) {
                            messageRecord.setMessage(num1[two]);
                            user.getUserRecords().addSendMessageRecords(messageRecord);
                        }
                    }
                }
            }
        }

        TreeMap<String, User> treeMap = new TreeMap<>();
        for (User user : users) {
            treeMap.put(user.getNumber(), user);
        }
        Iterator<User> t = treeMap.values().iterator();
        while (t.hasNext()) {
            User user = t.next();
            System.out.print(user.number);
            System.out.printf(" %.1f %.1f\n", user.calCost(), user.calBalance());
        }
    }
    static boolean checkm(String str) {

        if(str.matches("m-1\\d{10} 1\\d{10} ([a-zA-Z]|\\.|,| |\\d)*"))return true;
        return false;
    }
    static boolean checku(String s) {
        if(s.matches("u-1[0-9]{10} 3"))return true;
        return false;
    }
    public static class User {
        UserRecords userRecords = new UserRecords();
        double balance = 100;
        MessageCharging messageCharging;
        String number;

        public User(String number) {
            this.number = number;
        }
        double calBalance()
        {
            return getBalance() - calCost();
        }
        double calCost(){
            return messageCharging.calCost(userRecords);
        }
        public UserRecords getUserRecords() {
            return userRecords;
        }

        public double getBalance() {
            return balance;
        }
        public void setBalance(double balance) {
            this.balance = balance;
        }
        public String getNumber() {
            return number;
        }
        public void setNumber(String number) {
            this.number = number;
        }
    }
    public static class MessageRecord  {
        String message ;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
    public static class UserRecords {
        ArrayList<MessageRecord>sendMessageRecords = new ArrayList<MessageRecord>();
        ArrayList<MessageRecord>receiveMessageRecords = new ArrayList<MessageRecord>();
        public void addSendMessageRecords(MessageRecord sendMessageRecord)
        {
            sendMessageRecords.add(sendMessageRecord);
        }
        public ArrayList<MessageRecord> getSendMessageRecord() {
            return sendMessageRecords;
        }
    }
    public static class VendingMachine {
        int price = 80;
        int balance;
        int total;

        void setPrice(int price)
        {
            this.price =  price ;
            this.getFood();
        }
        public int showPrompt()
        {
            return 1;
        }

        public int insertMoney()
        {
            return 0;
        }

        public int  showBalance()
        {
            return 2;
        }

        void getFood()
        {
            if(balance >= price )
            {
                System.out.println("Here you are.");
                balance = balance - price ;
                total = total + price;
            }

        }
        public static void main(String[] args) {

        }

    }
    public static class MessageCharging {

        static double calCost(UserRecords userRecords) {
            double cost = 0;
            double sum = 0;
            for (MessageRecord s : userRecords.getSendMessageRecord()) {
                sum += Math.ceil(s.getMessage().length() / 10.0);
            }
            if (sum > 5) {
                cost = (sum - 5) * 0.3 + 0.4 + 0.3;
            } else if (sum > 3) {
                cost = (sum - 3) * 0.2 + 0.3;
            } else cost = 0.1 * sum;
            return cost;
        }
    }
}

最后附上这几次作业的类图:

 

 

 

 

 

 

 

 三、踩坑心得:

如果写代码能够提前将代码的框架构建好,这样我们在接下来的工作中会轻松很多,我们需要做的只是去修缮框架和填充内容,这样的工作量远远小于一边构造框架一边写具体代码,而且我认为提前构造框架也会降低写代码的难度。然后就是关于排序问题,我们需要掌握Java的一些类,来帮助我们排序,比如说:sort()方法和Comparable接口。
除此之外我们还需要熟练掌握我们所用ide的一些快捷方式,不管是eclipse还是idea,可以大大节省我们写代码的时间。

四、改进建议

对于电信计费系列问题,这是一个非常经典且有代表性的问题,如果我们当时没有做出来,在后面我们也应该再去搞懂

存在很多可以改进的地方,并且也仍有很多地方存在代码复制等问题,要改进我可以从这些地方着手。

五、总结

通过这次的题目初步掌握了类的基本用法,但是对于复杂的情况出现是还是不能够清晰的分析出题目中的需求。同时对于多态和继承、容器的知识的掌握不是很清晰明白,还需要去下功夫,好好学习对于本阶段,在内容上学习了是进一步对现实问题的分析和解决,通过完成这三道题,我们可以进一步了解java对现实应用的解决途径。三次题目中都需要用不同的正则表达式来解决问题,因此在过程中对于正则表达式的使用有了进一步的了解,

 

posted @ 2022-06-10 15:32  曾经-  阅读(265)  评论(0)    收藏  举报