Experiment two Java object-oriented programming

Source: Internet
Author: User
Tags getcolor staruml stringbuffer

Experiment two Java object-oriented Programming experiment report cover:
课程:Java程序设计  班级:1652班  姓名:王高源 学号:20165225指导教师:娄嘉鹏 实验日期:2018年4月16日实验时间:3:35 - 5:15 实验序号:实验二实验名称:Java面向对象程序设计实验题目:实验内容:1.初步掌握单元测试和TDD2.理解并掌握面向对象三要素:封装、继承、多态3.初步掌握UML建模4.熟悉S.O.L.I.D原则5.了解设计模式实验要求:1.实现百分制成绩转成“优、良、中、及格、不及格”五级制成绩的功能
Experimental content and steps: Note: The following many of the code is good for the teacher, only slightly modified. Unit Test
  • TDD steps: Pseudo-code (IDEA) → Test code (product expected function) → product code (to achieve expected functionality), this development method is called "Test-driven development"

  • Pseudo-code: Pseudo-code is independent of the specific programming language, do not write the specific programming language syntax-related statements (such as the allocation of memory with malloc, so only in C language programming), pseudo-code from the level of intent to solve the problem, in the end, pseudo-code is the most natural product code, the best comment.

  • Therefore, according to the experimental topic requirements, we should first write the corresponding "pseudo-code" to facilitate the completion of our programming, pseudo-code as follows:

    百分制转五分制:   如果成绩小于60,转成“不及格”   如果成绩在60与70之间,转成“及格”   如果成绩在70与80之间,转成“中等”   如果成绩在80与90之间,转成“良好”   如果成绩在90与100之间,转成“优秀”   其他,转成“错误”
  • The use of the language is clear and concise, then the pseudo-code to the product code.

  • Product Code: A program or machine language used to implement a specific function.

    public class MyUtil{public static String percentage2fivegrade(int grade){    //如果成绩小于0,转成“错误”    if ((grade < 0))        return "错误";        //如果成绩小于60,转成“不及格”    else if (grade < 60)        return "不及格";        //如果成绩在60与70之间,转成“及格”    else if (grade < 70)        return "及格";        //如果成绩在70与80之间,转成“中等”    else if (grade < 80)        return "中等";        //如果成绩在80与90之间,转成“良好”    else if (grade < 90)        return "良好";        //如果成绩在90与100之间,转成“优秀”    else if (grade <= 100)        return "优秀";        //如果成绩大于100,转成“错误”    else        return "错误";}}
  • After writing the product code, we also have to write the test code, to prove that their code is not a problem, so that the code can be assured to hand in the hands of users.

  • Test code: The code used to test the product code.

    public class MyUtilTest {public static void main(String[] args) {    // 百分制成绩是50时应该返回五级制的“不及格”    if(MyUtil.percentage2fivegrade(50) != "不及格")        System.out.println("test failed!");    else         System.out.println("test passed!");}}
  • The results of the operation are as follows:

    • It worked.

    • But only one group is a lazy suspicion, now we have to try the general situation:

    • And it worked.

    • Then look at the test in the unusual situation:

    • At this time we found the program bug: The judgment failed to ask for a score greater than 0, so we modify the source code, increase the judgment of negative points:

      public class MyUtil{   public static String percentage2fivegrade(int grade){   //如果成绩小于0,转成“错误”   if ((grade < 0))       return "错误";   //如果成绩小于60,转成“不及格”   else if (grade < 60)       return "不及格";   //如果成绩在60与70之间,转成“及格”   else if (grade < 70)       return "及格";   //如果成绩在70与80之间,转成“中等”   else if (grade < 80)       return "中等";   //如果成绩在80与90之间,转成“良好”   else if (grade < 90)       return "良好";   //如果成绩在90与100之间,转成“优秀”   else if (grade < 100)       return "优秀";   //如果成绩大于100,转成“错误”   else       return "错误";   }}
    • At this time to re-test the anomaly, found that passed:

    • It is gratifying to be congratulated.
    • But we haven't tested the boundary yet, so we're going to test the boundary conditions entered as "0,60,70,80,90,100" in the following code:

      public class MyUtilTest {public static void main(String[] args) {    //测试边界情况    if(MyUtil.percentage2fivegrade(0) != "不及格")        System.out.println("test failed 1!");    else if(MyUtil.percentage2fivegrade(60) != "及格")        System.out.println("test failed 2!");    else if(MyUtil.percentage2fivegrade(70) != "中等")        System.out.println("test failed 3!");    else if(MyUtil.percentage2fivegrade(80) != "良好")        System.out.println("test failed 4!");    else if(MyUtil.percentage2fivegrade(90) != "优秀")        System.out.println("test failed 5!");    else if(MyUtil.percentage2fivegrade(100) != "优秀")        System.out.println("test failed 6!");    else         System.out.println("test passed!"); }}
    • The result is as expected to be wrong:

    • We then changed the source code to "<=":

      public class MyUtil{   public static String percentage2fivegrade(int grade){   //如果成绩小于0,转成“错误”   if ((grade < 0))       return "错误";   //如果成绩小于60,转成“不及格”   else if (grade < 60)       return "不及格";   //如果成绩在60与70之间,转成“及格”   else if (grade < 70)       return "及格";   //如果成绩在70与80之间,转成“中等”   else if (grade < 80)       return "中等";   //如果成绩在80与90之间,转成“良好”   else if (grade < 90)       return "良好";   //如果成绩在90与100之间,转成“优秀”   else if (grade <= 100)       return "优秀";   //如果成绩大于100,转成“错误”   else       return "错误";   }}
    • Test again:

    • It worked.

    • It is worth mentioning that there is a unit test tool JUnit in Java to aid in TDD.

      The error came too abruptly:
    • Follow the steps of the teacher to walk accidentally appeared, thought is a network problem, the result changed the net also no use:

    • Then try to enter nothing directly from the browse repositories ... and then succeed.
    • Next click on the green installation, and then the error:

    • The gas is dead, and the next time, I find him good again ...

    • Back to the original question.

    • A everything was used to find Junit.jar from the Internet.

    • Then use the teacher's new method to test the previous code:

    • Success, and then maybe the version of the problem, my little green bar into a small green tick.

    • In fact, in accordance with the strategy before the failure, but fortunately there are good-looking help teaching sister gave me a bit, only to successfully complete the test.

Using STARUML to model the code in experiment two
  • The three elements of object-oriented (object-oriented) include: encapsulation, inheritance, polymorphism. Object-oriented thinking involves all aspects of software development, such as object-oriented analysis (OOA), Object-oriented design (OOD), and object-oriented programming (OOP). OOA decomposes The system according to the abstract key problem domain and focuses on what. Ood is an object-oriented implementation of the symbolic design system, which constructs the system into a "real-world" object in a way that is very close to the problem domain terminology, and focuses on how to implement the functional specification through the model. OOP is coded in a programming language (such as Java) on a design basis. The main line that runs through OOA, Ood, and OOP is abstraction .

  • Abstraction: The process of "seeking common ground and refine". The process of stripping together the same parts of several things and forming a product with a specific function is an abstraction. The result of the process abstraction is the function, and the result of the data abstraction is the abstract data type its obvious benefit is that (in the program design) The code is reduced in large repetition and improves efficiency.

  • Encapsulation: will be with a certain data and related behavior to be wrapped together to realize the information is hidden, the core content is modular and information hiding, and this is accompanied by the use of the interface.

  • Packaging:

    public class Dog {private String color;public String getColor() {return color;}public void setColor(String color) {this.color = color;}public String bark(){return "汪汪";}public String toString(){return "The Dog‘s color is " + this.getColor() +", and it shouts "+ this.bark() + "!";}}
  • Detection:

    public class DogTest {public static void main(String[] args) {Dog d = new Dog();d.setColor("Yellow");getInfo(d);}public static void getInfo(Dog d) {System.out.println(d.toString());}}
  • I used staruml to get out of the modeling (self-learning software is really tired OH):

Study StringBuffer in the way of TDD
    • The code for StringBuffer is as follows:
public class StringBufferDemo {  public static void main(String [] args) {    StringBuffer buffer = new StringBuffer();    buffer.append(‘S‘);    buffer.append("tringBuffer");    System.out.println(buffer.charAt(i));    System.out.println(buffer.capacity());    System.out.println(buffer.length());    System.out.println(buffer.indexOf("tring"));    System.out.println("buffer = " + buffer.toString());  
  • However, the teacher said that this code can not be used directly, after I put the seventh line of parentheses after the perfect run.

  • In the teacher-given use of JUnit learning Java, there are four things we need to test: charAt (), Capacity (), length (), and indexof.

  • Based on the above, our test code can be:

    import junit.framework.TestCase;import org.junit.Test;public class StringBufferDemoTest extends TestCase {StringBuffer a = new StringBuffer("StringBuffer");StringBuffer b = new StringBuffer("StringBufferStringBuffer");StringBuffer c = new StringBuffer("StringBufferStringBufferStringBuffer");@Testpublic void testcharAt() {    assertEquals(‘S‘,a.charAt(0));    assertEquals(‘e‘,b.charAt(10));    assertEquals(‘f‘,c.charAt(20));;}@Testpublic void testcapacity() {    assertEquals(28,a.capacity());    assertEquals(40,b.capacity());    assertEquals(52,c.capacity());}@Testpublic void testindexOf() {    assertEquals(0,a.indexOf("Str"));    assertEquals(3,b.indexOf("ing"));    assertEquals(10,c.indexOf("er"));}@Testpublic void testlength() {    assertEquals(12,a.length());    assertEquals(24,b.length());    assertEquals(48,c.length());}}
  • As a matter of course, let's test it:

    • It worked.
S.O.L.I.D Principles
    • SRP (Single Responsibility Principle, sole responsibility principle)
      objects provide a high degree of encapsulation of a single responsibility, and object changes depend only on the change of a single responsibility

    • OCP (open-closed Principle, open-closed principle)
      That is, to expand the open (function can be added), to modify the closed (source code can not be changed)

    • OCP implementation means: (1) abstraction and inheritance, (2) interface-oriented programming
      LSP (Liskov substitusion Principle,liskov substitution principle)
      The subclass must be able to be substituted by its base class, and the parent type object can be overridden by the quilt type Object
      ISP (Interface segregation Principle, interface separation principle)
      Customers should not rely on interfaces that they do not use

    • DIP (Dependency inversion Principle, dependency inversion principle)

    • Examples are as follows (self-learning number%6):

  Abstract class Data {abstract public void displayvalue ();}    Class Integer extends Data {int value;    Integer () {value=100;    } public void Displayvalue () {System.out.println (value);    }}class Short extends Data {short value;    Short () {value = 5225;    } public void Displayvalue () {System.out.println (value); }}abstract class Factory {abstract public Data createdataobject ();}    Class Intfactory extends Factory {public Data createdataobject () {return new Integer ();    }}class Shortfactory extends Factory {public Data createdataobject () {Return to new short ();    }}class Document {Data pd; Document (Factory pf) {PD = PF.    CreateDataObject (); } public void Displaydata () {PD.    Displayvalue ();    }}public class MyDoc {static Document D;        public static void Main (string[] args) {d = new Document (new Shortfactory ());    D.displaydata (); }}
    • This is a support for the short class of code, about the school number to take the remainder, if you want to change to other, only need to change here:
class ??? extends Data {    short value;    Short() {        value = 5225;    }    public void DisplayValue(){        System.out.println (value);    }}class ???Factory extends Factory {    public Data CreateDataObject(){        return new ???();    }}public class MyDoc {    static Document d;    public static void main(String[] args) {        d = new Document(new ???Factory());        d.DisplayData();    }}
    • This way the code conforms to the OCP principle, which makes the code extensible and maintainable.
Exercise: Designing a complex with TDD to implement plural classes
    • Pseudo code:
Complex类要输出实部,输出虚部,并按照a+bi的形式输出复数。Complex类中有两个变量,实部RealPart和虚部ImaginePart;,double RealPart;复数的实部double ImagePart;复数的虚部getRealPart():返回复数的实部getImagePart();返回复数的虚部setRealPart():设置复数的实部setImagePart();设置复数的虚部输出形式:a+bi(2)方法:// 定义构造函数public Complex()public Complex(double R,double I)// 定义公有方法:加减乘除Complex ComplexAdd(Complex a) 加Complex ComplexSub(Complex a) 减Complex ComplexMulti(Complex a) 乘Complex ComplexDiv(Complex a) 除//Override Objectpublic boolean equals(Object obj)public String toString():将复数输出成a+bi的格式。
    • Convert it into a product code:
  Import Java.util.scanner;public class Mycomplex {static int r;    static int i;    Private double m;    private double N;        public static int Getrealpart (int realpart) {r = Realpart;    return R;        } public static int getimaginepart (int imaginepart) {i = Imaginepart;    return i;        Public Mycomplex (double m, double n) {this.m = m;    THIS.N = n;    } public Mycomplex Add (Mycomplex c) {return new Mycomplex (M + c.m, n + C.N);    } public Mycomplex minus (Mycomplex c) {return new Mycomplex (M-C.M, N-C.N);    } public Mycomplex Multiply (Mycomplex c) {return new Mycomplex (M * c.m-n * C.N, M * C.N + n * c.m);        The public String toString () {string s = "";        if (n > 0) s = "(" + M + "+" + N + "I" + ")";        if (n = = 0) s = "(" + M + ")";        if (n < 0) s = "(" + M + n + "I" + ")";    return s; }}
    The
    • test code can be:
Import org.junit.test;import static org.junit.assert.*;p ublic class Mycomplextest {Mycomplex a=new Mycomplex (UP);    Mycomplex b=new Mycomplex (1,-4);    Mycomplex c=new Mycomplex (19,0);    Mycomplex d=new Mycomplex (0,-3);    Mycomplex e=new Mycomplex (0,0);        @Test public void Getrealpart () throws Exception {assertequals (1, Mycomplex.getrealpart (1));        Assertequals ( -1, Mycomplex.getrealpart (-1));        Assertequals (5, Mycomplex.getrealpart (5));        Assertequals (Mycomplex.getrealpart (22));        Assertequals ( -100, Mycomplex.getrealpart (-100));    Assertequals (0, Mycomplex.getrealpart (0));        } @Test public void Getimaginepart () throws Exception {assertequals (1, Mycomplex.getimaginepart (1));        Assertequals ( -1, Mycomplex.getimaginepart (-1));        Assertequals (5, Mycomplex.getimaginepart (5));        Assertequals (Mycomplex.getimaginepart (22));        Assertequals ( -100, Mycomplex.getimaginepart (-100)); Assertequals (0, MycompleX.getimaginepart (0));        } @Test public void Add () throws Exception {assertequals ("(2.0-2.0i)", A.add (b). ToString ());        Assertequals ("(20.0+2.0i)", A.add (c). ToString ());        Assertequals ("(1.0-1.0i)", A.add (d). toString ());    Assertequals ("(1.0+2.0i)", A.add (E). toString ());        } @Test public void Minus () throws Exception {assertequals ("(0.0+6.0i)", A.minus (b). ToString ());        Assertequals ("( -18.0+2.0i)", A.minus (c). ToString ());        Assertequals ("(1.0+5.0i)", A.minus (d). toString ());    Assertequals ("(1.0+2.0i)", A.minus (E). toString ());        } @Test public void multiply () throws Exception {assertequals ("(9.0-2.0i)", a.multiply (b). ToString ());        Assertequals ("(19.0+38.0i)", A.multiply (c). ToString ());        Assertequals ("(6.0-3.0i)", A.multiply (d). toString ());    Assertequals ("(0.0)", a.multiply (E). toString ()); }}
    • Test success:

Experience and summary of experiment
    • To tell you the truth, I'm not going to make up my program for this experiment. But fortunately, the teacher gave the template, only need to change a bit better.

    • In the experiment with code support, the more tired place is to see a lot of long blog, and the above mentioned some of the software operating methods you have to learn (although the teacher has given another UML modeling method, but I still use the other).

    • It's worth mentioning that what I learned this time will make it easier for me to fix code bugs and reduce the amount of effort needed to fix them later.

    • But anyway, the process is very tired, sometimes want to turn off all the blog, a good sleep, in the end I finished.

    • Still want to continue refueling Ah!

    • Code Cloud Link (This is the first time I've written git code.)

Experiment two Java object-oriented programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.