Java练习总结


前三次Java作业总结:

(1)前言:

涉及的考查要素: 第一次作业:重点考查Java的基本语法,是学习任何语言2的基础。 题量:9题     题目难度:易。

         第二次作业:重点考查对非法情况输入的判断以及不同情况的分类处理。 题量:3题   题目难度:中。

         第三次作业:重点考查对Java类的应用,以及类间关系的应用(聚合)。题量:4题    题目难度:较难。

(2)设计与分析(对较有代表性的题目进行分析):

1.串口字符解析

 

RS232是串口常用的通信协议,在异步通信模式下,串口可以一次发送5~8位数据,收发双方之间没有数据发送时线路维持高电平,相当于接收方持续收到数据“1”(称为空闲位),发送方有数据发送时,会在有效数据(5~8位,具体位数由通信双方提前设置)前加上1位起始位“0”,在有效数据之后加上1位可选的奇偶校验位和1位结束位“1”。请编写程序,模拟串口接收处理程序,注:假定有效数据是8位,奇偶校验位采用奇校验。

 

输入格式:

由0、1组成的二进制数据流。例如:11110111010111111001001101111111011111111101111

 

输出格式:

过滤掉空闲、起始、结束以及奇偶校验位之后的数据,数据之前加上序号和英文冒号。
如有多个数据,每个数据单独一行显示。
若数据不足11位或者输入数据全1没有起始位,则输出"null data",
若某个数据的结束符不为1,则输出“validate error”。
若某个数据奇偶校验错误,则输出“parity check error”。
若数据结束符和奇偶校验均不合格,输出“validate error”。
如:11011或11111111111111111。
例如:
1:11101011
2:01001101
3:validate error

源代码如下:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         Scanner input = new Scanner (System.in);
 8         String Number;
 9         int b=0;
10         int c=1;
11         Number = input.nextLine();
12         for(int a=0;a)
13         {
14             if(Number.charAt(a)=='0')
15             b++;
16         }
17         if(b==0)
18         {
19             System.out.print("null data");
20         }
21         else
22         {
23             
24         if(Number.length()<11)
25         {
26             System.out.print("null data");
27         }
28         else
29         for(int i=0;i<Number.length();)
30         {
31             int d=0;
32             char e='0';
33             if(Number.charAt(i)=='0')
34             {
35                 String num = Number.substring(i+1, i+11);
36                 for(int k=0;k)
37                 {
38                     if(num.charAt(k)=='1')
39                     {
40                         d++;
41                     }
42                 }
43                 if(d%2==0)
44                 {
45                     e='1';
46                 }
47                 else
48                 e='0';
49                 int j=0;
50                 if(num.charAt(j+9)!='1'&&num.charAt(j+8)==e)
51                 {
52                     System.out.println(c+":"+"validate error");
53                     c++;
54                 }
55                 else
56                 if(num.charAt(j+9)=='1'&&num.charAt(j+8)!=e)
57                 {
58                     System.out.println(c+":"+"parity check error");
59                     c++;
60                 }
61                 else
62                 if(num.charAt(j+9)!='1'&&num.charAt(j+8)!=e)
63                 {
64                     System.out.println(c+":"+"validate error");
65                     c++;
66                 }
67                 else
68                 if(num.charAt(j+9)=='1'&&num.charAt(j+8)==e)
69                 {
70                     System.out.println(c+":"+Number.substring(i+1, i+9));
71                     c++;
72                 }
73 
74                 i+=11;
75             }
76             else
77             i++;
78         }
79         }
80     }
81 
82 }

采坑心得:1.奇偶校验错误,没有弄清楚何为奇校验和偶校验,奇校验为:有效数据中1的个数为偶数则校验位为1,否则为0;

     2.注意结束符不为1和两者都不合格的输出结果是一样的。

     3.如有多组输出,注意分行以及序号的递增。

改进建议:有条件可以使用更加简洁的算法,以提升代码的质量。

2.用类解一元二次方程式 

定义一个代表一元二次方程ax2+bx+c=0的类QuadraticEquation,其属性为三个系数a、b、c(均为私有属性),类中定义的方法参考main方法中的代码。main方法源码:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args){
 5         Scanner input = new Scanner(System.in);
 6 
 7         double a = Double.parseDouble(input.next());
 8         double b = Double.parseDouble(input.next());
 9         double c = Double.parseDouble(input.next());
10         
11         if(a == 0){
12             System.out.println("Wrong Format");
13             System.exit(0);
14         }
15         
16         //create a QuadraticEquation object
17         QuadraticEquation equation = new QuadraticEquation(a, b, c);
18         //get value of b * b - 4 * a * c
19         double discriminant = equation.getDiscriminant();
20         
21         System.out.println("a=" + equation.getA() +
22                 ",b=" + equation.getB() + 
23                 ",c=" + equation.getC()+":");
24 
25         if (discriminant < 0) {
26           System.out.println("The equation has no roots.");
27         }
28         else if (discriminant == 0)
29         {
30           System.out.println("The root is " + 
31                   String.format("%.2f", equation.getRoot1()));
32         }
33         else // (discriminant >= 0)
34         {
35           System.out.println("The roots are " + 
36                   String.format("%.2f", equation.getRoot1()) 
37             + " and " +  String.format("%.2f", equation.getRoot2()));
38         }
39     }
40 }
41 
42 class QuadraticEquation{
43         //your code
44 }

注意:须提交完整源码,包括Main类。

输入格式:

在一行中输入a、b、c的值,可以用一个或多个空格或回车符分开。

输出格式:

  1. 当输入非法时,输出“Wrong Format”
  2. 当有一个实根时,输出(2行):
  • a=值,b=值,c=值:
  • The root is 值(保留两位小数)
  1. 当有两个实根时,输出(2行):
  • a=值,b=值,c=值:
  • The roots are 值1 and 值2(均保留两位小数) 

输入样例1:

在这里给出一组输入。例如:

1 84 -6653

输出样例1:

在这里给出相应的输出。例如:

a=1.0,b=84.0,c=-6653.0:
The roots are 49.74 and -133.74

输入样例2:

在这里给出一组输入。例如:

1.00 -2.000 1

输出样例2:

在这里给出相应的输出。例如:

a=1.0,b=-2.0,c=1.0:
The root is 1.00

源代码如下:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args){
 5         Scanner input = new Scanner(System.in);
 6 
 7         double a = Double.parseDouble(input.next());
 8         double b = Double.parseDouble(input.next());
 9         double c = Double.parseDouble(input.next());
10         
11         if(a == 0){
12             System.out.println("Wrong Format");
13             System.exit(0);
14         }
15         
16         //create a QuadraticEquation object
17         QuadraticEquation equation = new QuadraticEquation(a, b, c);
18         //get value of b * b - 4 * a * c
19         double discriminant = equation.getDiscriminant();
20         
21         System.out.println("a=" + equation.getA() +
22                 ",b=" + equation.getB() + 
23                 ",c=" + equation.getC()+":");
24 
25         if (discriminant < 0) {
26           System.out.println("The equation has no roots.");
27         }
28         else if (discriminant == 0)
29         {
30           System.out.println("The root is " + 
31                   String.format("%.2f", equation.getRoot1()));
32         }
33         else // (discriminant >= 0)
34         {
35           System.out.println("The roots are " + 
36                   String.format("%.2f", equation.getRoot1()) 
37             + " and " +  String.format("%.2f", equation.getRoot2()));
38         }
39     }
40 }
41 
42 class QuadraticEquation{
43         private double a;
44         private double b;
45         private double c;
46         public QuadraticEquation(double a,double b,double c){
47         
48             this.a = a;
49             this.b = b;
50             this.c = c;
51         }
52         public int getDiscriminant() {
53             double result;
54             result = (b*b)-4*a*c;
55             if(result<0)
56             return -1;
57             else
58             if(result>0)
59             return 1;
60             else
61             return 0;
62         }
63         public double getA() {
64             return a;
65         }
66         public double getB() {
67             return b;
68         }
69         public double getC() {
70             return c;
71         }
72         public double getRoot1() {
73             double root;
74             root = (-b+Math.sqrt((b*b)-4*a*c))/2*a;
75             return root;
76         }
77         public double getRoot2() {
78             double root;
79             root = (-b-Math.sqrt((b*b)-4*a*c))/2*a;
80             return root;
81         }
82 }

采坑心得:

  1. 无参构造方法及有参构造方法的应用,如何使用this;
  2. getter的使用,是返回一个数值,不是获取数值;
  3. 类的属性及方法的可见性,为私有还是公有(private与public);

改进建议:可以在主方法上加上setter的运用,以便代码有更好的可读性,增加读者的理解。

3.日期类设计

 参考题目集二中和日期相关的程序,设计一个类DateUtil,该类有三个私有属性year、month、day(均为整型数),其中,year∈[1820,2020] ,month∈[1,12] ,day∈[1,31] , 除了创建该类的构造方法、属性的getter及setter方法外,需要编写如下方法:

1 public boolean checkInputValidity();//检测输入的年、月、日是否合法
2 public boolean isLeapYear(int year);//判断year是否为闰年
3 public DateUtil getNextNDays(int n);//取得year-month-day的下n天日期
4 public DateUtil getPreviousNDays(int n);//取得year-month-day的前n天日期
5 public boolean compareDates(DateUtil date);//比较当前日期与date的大小(先后)
6 public boolean equalTwoDates(DateUtil date);//判断两个日期是否相等
7 public int getDaysofDates(DateUtil date);//求当前日期与date之间相差的天数
8 public String showDate();//以“year-month-day”格式返回日期值

应用程序共测试三个功能:

  1. 求下n天
  2. 求前n天
  3. 求两个日期相差的天数

注意:严禁使用Java中提供的任何与日期相关的类与方法,并提交完整源码,包括主类及方法(已提供,不需修改)

程序主方法如下:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner input = new Scanner(System.in);
 6         int year = 0;
 7         int month = 0;
 8         int day = 0;
 9 
10         int choice = input.nextInt();
11 
12         if (choice == 1) { // test getNextNDays method
13             int m = 0;
14             year = Integer.parseInt(input.next());
15             month = Integer.parseInt(input.next());
16             day = Integer.parseInt(input.next());
17 
18             DateUtil date = new DateUtil(year, month, day);
19 
20             if (!date.checkInputValidity()) {
21                 System.out.println("Wrong Format");
22                 System.exit(0);
23             }
24 
25             m = input.nextInt();
26 
27             if (m < 0) {
28                 System.out.println("Wrong Format");
29                 System.exit(0);
30             }
31 
32             System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " next " + m + " days is:");
33             System.out.println(date.getNextNDays(m).showDate());
34         } else if (choice == 2) { // test getPreviousNDays method
35             int n = 0;
36             year = Integer.parseInt(input.next());
37             month = Integer.parseInt(input.next());
38             day = Integer.parseInt(input.next());
39 
40             DateUtil date = new DateUtil(year, month, day);
41 
42             if (!date.checkInputValidity()) {
43                 System.out.println("Wrong Format");
44                 System.exit(0);
45             }
46 
47             n = input.nextInt();
48 
49             if (n < 0) {
50                 System.out.println("Wrong Format");
51                 System.exit(0);
52             }
53 
54             System.out.print(
55                     date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " previous " + n + " days is:");
56             System.out.println(date.getPreviousNDays(n).showDate());
57         } else if (choice == 3) {    //test getDaysofDates method
58             year = Integer.parseInt(input.next());
59             month = Integer.parseInt(input.next());
60             day = Integer.parseInt(input.next());
61 
62             int anotherYear = Integer.parseInt(input.next());
63             int anotherMonth = Integer.parseInt(input.next());
64             int anotherDay = Integer.parseInt(input.next());
65 
66             DateUtil fromDate = new DateUtil(year, month, day);
67             DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);
68 
69             if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {
70                 System.out.println("The days between " + fromDate.showDate() + 
71                         " and " + toDate.showDate() + " are:"
72                         + fromDate.getDaysofDates(toDate));
73             } else {
74                 System.out.println("Wrong Format");
75                 System.exit(0);
76             }
77         }
78         else{
79             System.out.println("Wrong Format");
80             System.exit(0);
81         }        
82     }
83 }

输入格式:

有三种输入方式(以输入的第一个数字划分[1,3]):

  • 1 year month day n //测试输入日期的下n天
  • 2 year month day n //测试输入日期的前n天
  • 3 year1 month1 day1 year2 month2 day2 //测试两个日期之间相差的天数

输出格式:

  • 当输入有误时,输出格式如下:
  • Wrong Format
  • 当第一个数字为1且输入均有效,输出格式如下:
  • year1-month1-day1 next n days is:year2-month2-day2

  • 当第一个数字为2且输入均有效,输出格式如下:
  • year1-month1-day1 previous n days is:year2-month2-day2

  • 当第一个数字为3且输入均有效,输出格式如下:
  • The days between year1-month1-day1 and year2-month2-day2 are:值

 源代码如下:

  1 import java.util.Scanner;
  2 
  3 public class Main {
  4     public static void main(String[] args) {
  5         Scanner input = new Scanner(System.in);
  6         int year = 0;
  7         int month = 0;
  8         int day = 0;
  9 
 10         int choice = input.nextInt();
 11 
 12         if (choice == 1) { // test getNextNDays method
 13             int m = 0;
 14             year = Integer.parseInt(input.next());
 15             month = Integer.parseInt(input.next());
 16             day = Integer.parseInt(input.next());
 17 
 18             DateUtil date = new DateUtil(year, month, day);
 19 
 20             if (!date.checkInputValidity()) {
 21                 System.out.println("Wrong Format");
 22                 System.exit(0);
 23             }
 24 
 25             m = input.nextInt();
 26 
 27             if (m < 0) {
 28                 System.out.println("Wrong Format");
 29                 System.exit(0);
 30             }
 31 
 32             System.out.print(date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " next " + m + " days is:");
 33             System.out.println(date.getNextNDays(m).showDate());
 34         } else if (choice == 2) { // test getPreviousNDays method
 35             int n = 0;
 36             year = Integer.parseInt(input.next());
 37             month = Integer.parseInt(input.next());
 38             day = Integer.parseInt(input.next());
 39 
 40             DateUtil date = new DateUtil(year, month, day);
 41 
 42             if (!date.checkInputValidity()) {
 43                 System.out.println("Wrong Format");
 44                 System.exit(0);
 45             }
 46 
 47             n = input.nextInt();
 48 
 49             if (n < 0) {
 50                 System.out.println("Wrong Format");
 51                 System.exit(0);
 52             }
 53 
 54             System.out.print(
 55                     date.getYear() + "-" + date.getMonth() + "-" + date.getDay() + " previous " + n + " days is:");
 56             System.out.println(date.getPreviousNDays(n).showDate());
 57         } else if (choice == 3) {    //test getDaysofDates method
 58             year = Integer.parseInt(input.next());
 59             month = Integer.parseInt(input.next());
 60             day = Integer.parseInt(input.next());
 61 
 62             int anotherYear = Integer.parseInt(input.next());
 63             int anotherMonth = Integer.parseInt(input.next());
 64             int anotherDay = Integer.parseInt(input.next());
 65 
 66             DateUtil fromDate = new DateUtil(year, month, day);
 67             DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);
 68 
 69             if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {
 70                 System.out.println("The days between " + fromDate.showDate() + 
 71                         " and " + toDate.showDate() + " are:"
 72                         + fromDate.getDaysofDates(toDate));
 73             } else {
 74                 System.out.println("Wrong Format");
 75                 System.exit(0);
 76             }
 77         }
 78         else{
 79             System.out.println("Wrong Format");
 80             System.exit(0);
 81         }        
 82     }
 83 }
 84 class DateUtil {
 85     private int year;
 86     private int month;
 87     private int day;
 88     public DateUtil(int year,int month,int day) {
 89         this.year = year;
 90         this.month = month;
 91         this.day = day;
 92     }
 93     public int getYear() {
 94         return year;
 95     }
 96     
 97     public int getMonth() {
 98         return month;
 99     }
100     
101     public int getDay() {
102         return day;
103     }
104     
105     
106     boolean a = isLeapYear(year);
107     int[] rmonth = new int[]{0,31,29,31,30,31,30,31,31,30,31,30,31};
108     int[] pmonth = new int[]{0,31,28,31,30,31,30,31,31,30,31,30,31};
109     
110     
111     public boolean checkInputValidity(){
112         //检测输入的年、月、日是否合法
113         
114         if(year>=1820&&year<=2020&&month>=1&&month<=12&&day>=1&&day<=31)
115         {
116             
117             if(a = true)
118             {
119                 if(day<=rmonth[month])
120                 {
121                     return true;
122                 }
123                 else 
124                 return false;
125             }
126             else
127             {
128                 if(day<=pmonth[month])
129                 {
130                     return true;
131                 }
132                 else 
133                 return false;
134             }
135         }
136         else
137         return false;
138     }
139     
140     public boolean isLeapYear(int year){
141         //判断year是否为闰年
142         if( (year%4==0&&year%100!=0) || year%400==0 )
143         return true;
144         else
145         return false;
146     }
147     
148     public DateUtil getNextNDays(int n){
149         //取得year-month-day的下n天日期
150         long  days = 0;
151         days =(long) day+(long) n;
152         while(true)
153         {
154             if(isLeapYear(year)==true)
155             {
156                 while(days>rmonth[month])
157                 {
158                     days = days - rmonth[month];
159                     month = month + 1;
160                     if(month == 13)
161                     {
162                         month = 1;
163                         year = year + 1;
164                         break;
165                     }
166                 }
167             }
168             else
169             if(isLeapYear(year)==false)
170             {
171                 while(days>pmonth[month])
172                 {
173                     days = days - pmonth[month];
174                     month = month + 1;
175                     if(month == 13)
176                     {
177                         month = 1;
178                         year = year + 1;
179                         break;
180                     }
181                 }
182             }
183             if(days<=rmonth[month])
184             {
185                 break;
186             }
187             
188         }
189         DateUtil e = new DateUtil(year,month,(int) days);
190         return e;
191     }
192     public DateUtil getPreviousNDays(int n){
193         //取得year-month-day的前n天日期
194         long  days = 0;
195         days = day - n;
196         while(true)
197         {
198              if(isLeapYear(year))
199              {
200                  while(days<1)
201                  {
202                      month = month - 1;
203                      days = days + rmonth[month];
204                      if(month == 0)
205                      {
206                          month = 13;
207                          year = year - 1;
208                          break;
209                      }
210                  }
211                  
212              }
213              else
214              {
215                  while(days<1)
216                  {
217                      month = month - 1;
218                      days = days + pmonth[month];
219                      if(month == 0)
220                      {
221                          month = 13;
222                          year = year - 1;
223                          break;
224                      }
225                  }
226                  
227              }
228              if(days>1)
229              {
230                  break;
231              }
232              
233         }
234         DateUtil f = new DateUtil(year,month,(int) days);
235         return f;    
236     }
237     
238     
239     
240     public boolean compareDates(DateUtil date){
241         //比较当前日期与date的大小(先后)
242         if(year<date.year)
243         {
244             return false;
245         }
246         else
247         {
248             if(year>date.year)
249             {
250                 return true;
251             }
252             else
253             {
254                 if(month<date.month)     
255                 {
256                     return false;
257                 }
258                 else
259                 {
260                     if(month>date.month)
261                     {
262                         return true;
263                     }
264                     else
265                     {
266                         if(day<date.day)
267                         {
268                             return false;
269                         }
270                         else
271                         return true;
272                     }
273                 }
274                 
275             }            
276         }
277 
278     }
279     public boolean equalTwoDates(DateUtil date){
280         //判断两个日期是否相等
281         if(year==date.year&&month==date.month&&day==date.day)
282         {
283             return true;
284         }
285         else
286         return false;
287     }
288     public int getDaysofDates(DateUtil date){
289         //求当前日期与date之间相差的天数
290         
291         int c = 0;
292         boolean    a=isLeapYear(year);
293         for(int i=1;i)
294         {
295             if(isLeapYear(i))
296             c=366+c;
297             else
298             c=365+c;
299         }
300         if(a==true)
301         {
302             for(int j=1;j)
303             {
304                 c+=rmonth[j];
305             }
306         }
307         else
308         for(int j=1;j)
309         {
310             c+=pmonth[j];
311         }
312         c+=day;
313         
314         
315         int d = 0;
316         boolean    b=isLeapYear(date.year);
317         for(int i=1;i)
318         {
319             if(isLeapYear(i))
320             d=366+d;
321             else
322             d=365+d;
323         }
324         if(b==true)
325         {
326             for(int j=1;j)
327             {
328                 d+=rmonth[j];
329             }
330         }
331         else
332         for(int j=1;j)
333         {
334             d+=pmonth[j];
335         }
336         d+=date.day;
337         
338         
339         if(c>d)
340         {
341             return c-d;
342         }
343         else
344         return d-c;
345         
346         }
347     
348     public String showDate(){
349         //以“year-month-day”格式返回日期值
350     return String.format("%d-%d-%d",year,month,day);
351     }    
352 }

采坑心得:1.检验输入是否合法的时候,day的检验并不只是【1,31】,要根据平年还是闰年以及每个月的最大天数来判断,像平年2月只有28天,有的月数只有30天等等。

     2.求下n天以及前n天的时候,要注意12月份过了就是1月份,1月份之前是12月份,以及每个月的天数的最大值不同,比如:平年3月1号的前1天是2月28号等等。

     3.因为n没有限制,所以同时要考虑到跨年的情况,同时要判断年份的平年还是闰年。

     4.求两个日期相差的天数时,可以以一个日期为基准计算两个日期与其相差的天数,再相减。以简化代码步骤。

改进建议:可以在源代码的基础上进行类的降耦合,以实现更低的耦合性,提升代码质量。

4.日期问题面向对象设计(聚合)

参考题目3的要求,设计如下几个类:DateUtil、Year、Month、Day,其中年、月、日的取值范围依然为:year∈[1900,2050] ,month∈[1,12] ,day∈[1,31] , 设计类图如下:

应用程序共测试三个功能:

  1. 求下n天
  2. 求前n天
  3. 求两个日期相差的天数

注意:严禁使用Java中提供的任何与日期相关的类与方法,并提交完整源码,包括主类及方法(已提供,不需修改)

输入格式:

有三种输入方式(以输入的第一个数字划分[1,3]):

  • 1 year month day n //测试输入日期的下n天
  • 2 year month day n //测试输入日期的前n天
  • 3 year1 month1 day1 year2 month2 day2 //测试两个日期之间相差的天数

输出格式:

    • 当输入有误时,输出格式如下:
    • Wrong Format
    • 当第一个数字为1且输入均有效,输出格式如下:
    • year-month-day
    • 当第一个数字为2且输入均有效,输出格式如下:
    • year-month-day
    • 当第一个数字为3且输入均有效,输出格式如下:
    • 天数值

源代码如下:

  1 import java.util.Scanner;
  2 
  3 public class Main {
  4     public static void main(String[] args) {
  5         Scanner input = new Scanner(System.in);
  6         int year = 0;
  7         int month = 0;
  8         int day = 0;
  9 
 10         int choice = input.nextInt();
 11 
 12         if (choice == 1) { // test getNextNDays method
 13             int m = 0;
 14             year = Integer.parseInt(input.next());
 15             month = Integer.parseInt(input.next());
 16             day = Integer.parseInt(input.next());
 17 
 18             DateUtil date = new DateUtil(year, month, day);
 19 
 20             if (!date.checkInputValidity()) {
 21                 System.out.println("Wrong Format");
 22                 System.exit(0);
 23             }
 24 
 25             m = input.nextInt();
 26 
 27             if (m < 0) {
 28                 System.out.println("Wrong Format");
 29                 System.exit(0);
 30             }
 31             System.out.println(date.getNextNDays(m).showDate());
 32         } else if (choice == 2) { // test getPreviousNDays method
 33             int n = 0;
 34             year = Integer.parseInt(input.next());
 35             month = Integer.parseInt(input.next());
 36             day = Integer.parseInt(input.next());
 37 
 38             DateUtil date = new DateUtil(year, month, day);
 39 
 40             if (!date.checkInputValidity()) {
 41                 System.out.println("Wrong Format");
 42                 System.exit(0);
 43             }
 44 
 45             n = input.nextInt();
 46 
 47             if (n < 0) {
 48                 System.out.println("Wrong Format");
 49                 System.exit(0);
 50             }
 51             System.out.println(date.getPreviousNDays(n).showDate());
 52         } else if (choice == 3) {    //test getDaysofDates method
 53             year = Integer.parseInt(input.next());
 54             month = Integer.parseInt(input.next());
 55             day = Integer.parseInt(input.next());
 56 
 57             int anotherYear = Integer.parseInt(input.next());
 58             int anotherMonth = Integer.parseInt(input.next());
 59             int anotherDay = Integer.parseInt(input.next());
 60 
 61             DateUtil fromDate = new DateUtil(year, month, day);
 62             DateUtil toDate = new DateUtil(anotherYear, anotherMonth, anotherDay);
 63 
 64             if (fromDate.checkInputValidity() && toDate.checkInputValidity()) {
 65                 System.out.println(fromDate.getDaysofDates(toDate));
 66             } else {
 67                 System.out.println("Wrong Format");
 68                 System.exit(0);
 69             }
 70         }
 71         else{
 72             System.out.println("Wrong Format");
 73             System.exit(0);
 74         }        
 75     }
 76 }
 77 class DateUtil {
 78     public DateUtil(){
 79         super();
 80         // TODO Auto-generated constructor stub
 81     }
 82         Day day;
 83         public DateUtil(int d, int m, int y) {
 84             this.day = new Day(d,m,y);
 85         }
 86         public Day getDay() {
 87             return day;
 88         }
 89         public void setDay(Day d) {
 90             this.day = d;
 91         }
 92 
 93         public boolean checkInputValidity(){
 94             //检测输入的年、月、日是否合法
 95             if(this.getDay().getMonth().getYear().validate()==true&&this.getDay().getMonth().validate()==true&&day.validate()==true)
 96             {
 97                 return true;
 98             }
 99             else
100             return false;
101         }
102         public boolean compareDates(DateUtil date){
103             //比较当前日期与date的大小(先后)
104             if(date.getDay().getMonth().getYear().getValue()<this.getDay().getMonth().getYear().getValue())
105                 return false;
106             else 
107             if(date.getDay().getMonth().getYear().getValue()==this.getDay().getMonth().getYear().getValue()&&date.getDay().getMonth().getValue()<this.getDay().getMonth().getValue())
108                 return false;
109             else 
110             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())
111                 return false;
112             else
113                 return true;
114         }
115         public boolean equalTwoDates(DateUtil date){
116             //判断两个日期是否相等
117             if(this.getDay().getMonth().getYear().getValue()==date.getDay().getMonth().getYear().getValue()&&this.getDay().getMonth().getValue()==date.getDay().getMonth().getValue()&&this.getDay().getValue()==date.getDay().getValue())
118             {
119                 return true;
120             }
121             else
122             return false;
123         }
124         public String showDate(){
125             //以“year-month-day”格式返回日期值
126         return String.format("%d-%d-%d",this.getDay().getMonth().getYear().getValue(),this.getDay().getMonth().getValue(),this.getDay().getValue());
127         }
128         public DateUtil getNextNDays(int n){
129             //取得year-month-day的下n天日期
130             long  days = 0;
131             int y;
132             int m;
133             y = this.getDay().getMonth().getYear().getValue();
134             m = this.getDay().getMonth().getValue();
135             days =(long) this.getDay().getValue()+(long) n;
136             while(true)
137             {
138                 if(new Year(y).isLeapYear())
139                 {
140                     this.getDay().mon_maxnum[1] = 29;
141                     while(days>this.getDay().mon_maxnum[m-1])
142                     {
143                         days = days - this.getDay().mon_maxnum[m-1];
144                         m = m + 1;
145                         if(m == 13)
146                         {
147                             m = 1;
148                             y = y + 1;
149                             break;
150                         }
151                     }
152                 }
153                 else
154                 if(new Year(y).isLeapYear()==false)
155                 {
156                     this.getDay().mon_maxnum[1] = 28;
157                     while(days>this.getDay().mon_maxnum[m-1])
158                     {
159                         days = days - this.getDay().mon_maxnum[m-1];
160                         m = m + 1;
161                         if(m == 13)
162                         {
163                             m = 1;
164                             y = y + 1;
165                             break;
166                         }
167                     }
168                 }
169                 if(days<this.getDay().mon_maxnum[m-1])
170                 {
171                     break;
172                 }
173                 
174             }
175             DateUtil e = new DateUtil(y,m,(int) days);
176             return e;
177         }
178         public DateUtil getPreviousNDays(int n){
179             //取得year-month-day的前n天日期
180             long  days = 0;
181             int y;
182             int m;
183             y = this.getDay().getMonth().getYear().getValue();
184             m = this.getDay().getMonth().getValue();
185             days = this.getDay().getValue() - n;
186             while(true)
187             {
188                  if(new Year(y).isLeapYear())
189                  {
190                     this.getDay().mon_maxnum[1] = 29;
191                      while(days<1)
192                      {
193                          m = m - 1;
194                          if(m!= 0 )
195                          days = days + this.getDay().mon_maxnum[m-1];
196                          if(m == 0)
197                          {
198                              days = days + this.getDay().mon_maxnum[11];
199                              m = 12;
200                              y = y - 1;
201                              break;
202                          }
203                      }
204                  }
205                  else
206                  {
207                     this.getDay().mon_maxnum[1] = 28;
208                      while(days<1)
209                      {
210                          m = m - 1;
211                          if(m!=0)
212                          days = days + this.getDay().mon_maxnum[m-1];
213                          if(m == 0)
214                          {
215                              days = days + this.getDay().mon_maxnum[11];
216                              m = 12;
217                              y = y - 1;
218                              break;
219                          }
220                      }
221                      
222                  }
223                  if(days>1)
224                  {
225                      break;
226                  }
227                  
228             }
229             DateUtil f = new DateUtil(y,m,(int) days);
230             return f;    
231         }
232         public int getDaysofDates(DateUtil date){
233             //求当前日期与date之间相差的天数
234             
235             int c = 0;
236             int y;
237             int m;
238             int d;
239             y = this.getDay().getMonth().getYear().getValue();
240             m = this.getDay().getMonth().getValue();
241             d = this.getDay().getValue();
242             for(int i=1;i)
243             {
244                 if(new Year(i).isLeapYear())
245                 c=366+c;
246                 else
247                 c=365+c;
248             }
249             if(this.getDay().getMonth().getYear().isLeapYear())
250             {
251                 this.getDay().mon_maxnum[1] = 29;
252                 for(int j=1;j)
253                 {
254                     c+=this.getDay().mon_maxnum[j-1];
255                 }
256             }
257             else
258             for(int j=1;j)
259             {
260                 c+=this.getDay().mon_maxnum[j-1];
261             }
262             c+=d;
263 
264             int g = 0;;
265             for(int i=1;i)
266             {
267                 if(new Year(i).isLeapYear())
268                 g=366+g;
269                 else
270                 g=365+g;
271             }
272             if(date.getDay().getMonth().getYear().isLeapYear())
273             {
274                 date.getDay().mon_maxnum[1] = 29;
275                 for(int j=1;j)
276                 {
277                     g+=date.getDay().mon_maxnum[j-1];
278                 }
279             }
280             else
281             for(int j=1;j)
282             {
283                 g+=date.getDay().mon_maxnum[j-1];
284             }
285             g+=date.getDay().getValue();
286             
287             
288             if(c>g)
289             {
290                 return c-g;
291             }
292             else
293             return g-c;
294             
295             }
296 }
297 class Day {
298     public Day() {
299         super();
300         // TODO Auto-generated constructor stub
301     }
302     private int value;
303     Month month;
304     int mon_maxnum[]={31,28,31,30,31,30,31,31,30,31,30,31};
305     
306     public Day(int yearValue, int monthValue, int dayValue) {
307         this.month = new Month(yearValue, monthValue);
308         this.value = dayValue;
309     }
310     public int getValue() {
311         return value;
312     }
313     public void setValue(int value) {
314         this.value = value;
315     }
316     public Month getMonth() {
317         return month;
318     }
319     public void setMonth(Month value) {
320         this.month = value;
321     }
322     public void resetMin() {
323         value = 1;
324     }
325     public void resetMax() {
326         value = mon_maxnum[month.getValue()-1];
327     }
328     public boolean validate() {
329         if(this.getMonth().getYear().isLeapYear())
330         this.mon_maxnum[1] = 29;
331         if(value>=1&&value<=mon_maxnum[month.getValue()-1])                                                                                                                                                                                                                                                                               
332             return true;
333         else
334             return false;
335     }
336     public void dayIncrement() {
337         value++;
338     }
339     public void dayReduction() {
340         value--;
341     }
342 }
343 class Month {
344      public Month() {
345             super();
346             // TODO Auto-generated constructor stub
347         }
348          private int value;
349         Year year;
350     public Month(int yearValue, int monthValue) {
351         this.year =new Year(yearValue);
352         this.value = monthValue;
353     }
354     public int getValue() {
355         return value;
356     }
357     public void setValue(int value) {
358         this.value = value;
359     }
360     public Year getYear() {
361         return year;
362     }
363     public void setYear(Year year) {
364         this.year = year;
365     }
366     public void resetMin() {
367         value = 1;
368     }
369     public void resetMax() {
370         value = 12;
371     }
372     public boolean validate() {
373         if(value>=1&&value<=12)
374         return true;
375         else
376         return false;
377     }
378     public void monthIncrement() {
379         value++;
380     }
381     public void monthReduction() {
382         value--;
383     }
384      
385      
386      
387 }
388 class Year {
389     public Year() {
390         super();
391         // TODO Auto-generated constructor stub
392     }
393     private int value;
394     public Year(int value) {
395         this.value = value;
396     }
397     public int getValue() {
398         return value;
399     }
400     public void setValue(int value) {
401         this.value = value;
402     }
403     public boolean isLeapYear(){
404         //判断year是否为闰年
405         if( (value%4==0&&value%100!=0) || value%400==0 )
406         return true;
407         else
408         return false;
409     }
410     public boolean validate() {
411         if(value>=1900&&value<=2050)
412         return true;
413         else
414         return false;
415     }
416     public void yearIncrement() {
417         value++;
418     }
419     public void yearReduction() {
420         value--;
421     }
422 }

 采坑心得:1.不同类之间的联系,以及之间的调用关系,严格按照类图的格式来编写程序。

      2.getter与setter的运用,合理传参数,以及DateUtil类的主要方法,必须在原方法的基础上转换成类的调用。

 改进建议:在原来第3题的基础上可以适当改进一下算法,以简化程序,使代码更简洁。

总结:

三次题目集的完成,是一个从易到难的过程,从开始的语言基础到类相关的运用,面向对象程序设计的大门已然开启,从这三个题目集的练习我熟悉了

正确运用循环及条件来控制序,如何正确判断输入的边界值,对数值进行判断与处理,以及如何运用Java类相关的知识来简化一些题目的流程,使其

条理清晰,更通俗易懂;面对一些复杂的问题时如何将其程化,数字化,用面向对象的思维来思考问题,处理问题,解决问题;同时也发现了自己的

程序方面的一些不足之处,编写速度,代码的算法的优越性等等,在这些方面,我还应该加强。同时对教师、课程、作业、实验、课上及课下组织方

等方面,我觉得十分合理,老师这么做一定有他的道理,为了帮助我们更好的学习专业知识等等。

 

相关