Introduction to Java Packaging Ideas (crossword puzzle 2.0)

Source: Internet
Author: User

First, Introduction

  This chapter upgrades the crossword puzzle game 1.0 in the first article , and then gives the reader a brief introduction to Some of the knowledge and implementation ideas of the packaging concept in JAVA.

Ii. Introduction to the concept of encapsulation

 Three basic features are proposed in object-oriented programming: encapsulation, inheritance and polymorphism. Among them, encapsulation is the basis of inheritance and polymorphism. If the meaning of encapsulation is not well understood, then the learning of inheritance and polymorphism cannot be discussed. Therefore, in order to better understand the encapsulation idea, we will solve the following problems (2.1):

    • What is encapsulation?
    • Why do we need encapsulation?
    • What are the characteristics of encapsulation?
    • How is encapsulation implemented?

The idea of encapsulation, from its origins, has been a long time. As early as Aristotle's time, he had writings on types. And this type is the origin of the encapsulation idea. In other words, an abstraction of an object with similar behavior and attributes is divided into a group, and the merging process of this object is called encapsulation.

We just need to pull out their shared parts for use. In JAVA It is called the encapsulated module, which is typical of class.

The advantage of this idea is that, on the basis of the problem-based description, the feasible methodological guiding ideology is put forward. The question of how to do it. The core of his thinking is splitting up and splitting a big problem into a lot of small problems, but here's one thing to note: This is not an unrestricted split, his purpose is just to make the problem more efficient to solve. So, the degree to which we divide is that we can solve him by studying and studying in a short time.

Since the idea of encapsulation is just a matter of breaking the big question, then we can divide the programmer into two categories- the creator of the encapsulated object and the consumer of the encapsulated object.

For the purpose of division of labor, the purpose of the user is only to collect a variety of classes used to achieve rapid application development, what they need is the function of these things rather than the implementation. But the creator is the opposite.

This creates a contradiction in whether the object in the class can be accessed arbitrarily. The answer is negative.

In any relationship, it is important to have a boundary that is respected by all the aspects involved in the relationship. If all the members of the class are available to anything, then the user of the class can do anything to the class without being constrained. This is one of the most important reasons for the bug that many programs are using-the user's input is not legal, and the creation of the program does not respond to a strong refusal (deny any illegal input).

Why do we need a strong rejection mechanism? In practice, we will encounter various, if we choose to ignore him, often will have disastrous consequences, this is not uncommon examples of neglect. such as the warning of earthquakes and the development of serious illnesses. So, I have a desire to have a mechanism to solve any problems encountered, which is called over-optimization in programming. However, it is virtually impossible and difficult to complete. Because the concept of the problem is too broad and involves specific situations. So, when we don't know the situation, we should set the situation and draw the scope. The establishment of the scope, on behalf of the refusal, what can be entered, what can not. This is also the idea of encapsulation, another important concept - to establish the scope.

Therefore, the creator needs to make hidden and restricted access to some parts of the code.

In this case, access control hides the parts that the consumer should not touch- This is part of the internal operation for the data type, but is not part of the interface that the consumer needs to solve a particular problem. (In other words, this is only a service to the user, because they can easily see that things are important to him and which can be overlooked.) )

There is a second reason for existence, which is in the creator's position. The creator wants to be able to achieve the maximum goal through a small amount of change. If you allow creators to change the way they work internally without worrying about affecting the user. That's a good way to do it. For example, I found that changing a particular encapsulated object , class, can improve the efficiency of this program object. At this point, if the interface and implementation can be clearly separated and protected, then you can do the job easily.

As a result,JAVA has made public,private(private), protected in defining internal boundaries. (Protection) The division of these three definitions.

These access-specific words determine who can be used by what is defined immediately after.

    • public: Common part, anyone can use.
    • Private: It's like a privategarden, and no one can access this element except for the type creator and the internal method of the type. (For this purpose, so he ends up with return(return value), otherwise the caller will never know what your reply is.) )
    • Protected: Protection type, this is dedicated to inheritance, later in the introduction. the only difference between him and Private is that the inheriting class can access it.

Finally, there is a default form of access, called Package access. If you do not use any of the above to access the specified word, he will play a role, the class can access other class members in the same package, but outside of this scope, its members in addition to the creator of the class and its own internal methods can be accessed, the rest will be rejected, plainly speaking is the larger version of the Private type.

Immediately after, our module has been designed according to the access rights, then there will be some demand -- We hope that our creation should be a useful code unit, he can call repeatedly, and this call the simplest way is to create it. This approach is also called reuse. Although, in fact, sometimes this kind of reuse will be unsatisfactory.

Because of the new module, you can have any number of other objects of any type in any way. However, the composition of the way there are static and dynamic two aspects. Where static is called a combination, dynamic is called aggregation.

Because reuse can bring great flexibility. The member objects of the new module are also usually declared privateso that theuser cannot access them and the bugis reduced. This also allows you to modify them without interfering with the main program code. At that time, it can also be modified while the program is running. From the feature of reuse, it is much like the concept of inheritance, but he is simpler and smaller. Therefore, when building a new module, it is preferable to use it, and the concept of inheritance and its implementation are discussed later.

Figure 2.1 Introduction to packaging ideas

Third, build their own applications

3.1 Requirements:

Change the 1.0to make a crossword puzzle game with a different level 2.0: Match the user input letters, and the whole pair indicates the user wins.

3.2Concrete implementation of encapsulation idea

3.2 as shown, we need the following several modules:

    • Requires an interface that can read and write to the console.
    • A letter generator is required.
    • A match is required that matches the user input data with the generator generating letters (the matching device has a mechanism to determine how many letters the user has matched correctly).
    • A loop counter is required (to alert the user to the number of times left and count the number of cycles).

One of the things we need to change is the random number generator in 1.0, which changes it to a letter producer. and the comparison module in the 1.0, separately mentioned out of the package, change its function as a matching device.

Program Data structure:

1.char type array input: Used to save user guessing alphabetic data.

2.char type array temp: Used to hold letters generated by the letter generator.

3, array of type int result: Used to save the judgment result. (the array contains two elements, the first element is used to hold the number of letters that are fully guessed, and the second element is used to hold the user guessing the number of letters (the characters are correct but the position is incorrect).)

4,int type variable num: Stores the total number of times the user has played the game.

Figure 3.2 puzzle game 2.0

3.3Algorithmic Flow

Iv. Concrete Implementation
Package Abcgame;import Java.util.scanner;public class Abcgame {/** * Riddle Program 2.0 * @param input for saving user guessing alphabetic data * @param temp Used to hold letters generated by the letter generator * @param result is used to save the judging result * @param num stores the total number of times the user has played the game */public static void Main (string[] args) {//Main program Directory CH ar[] input = null;char[] temp = generate (); int[] result = new Int[2];int num = 0; Scanner s = new Scanner (system.in); System.out.println ("You are welcome to participate in the game!" "); System.out.println ("The game begins! Please enter five different letters: (exit--exit, your health value is "+ (temp.length*100) +", each error is deducted 10 points) "); while (true) {String inputstr = S.next (). Trim (). toUpperCase (); if ("EXIT". Equals (Inputstr)) {System.out.println ("Thank you for participating, goodbye!") "); break;} Input =inputstr.tochararray (); for (int k = 0;k < input.length;k++) {for (int u = 0;u < input.length;u++) {if (k! = u &A mp;& Input[k] = = Input[u]) {System.out.print ("Please start again and enter the correct five-bit different letters!! "); System.exit (0);//program ends normally. }}}result = Check (temp,input), if (result[0] = = temp.length) {System.out.println ("Congratulations, you guessed it!") Your score is "+ (temp.length*100-num*10)"; else {num++; System.out.println ("You guessed to the" +result[1]+ "character, whoseThe "+result[0]+" characters are correct! "); SYSTEM.OUT.PRINTLN ("Your health is left" + (temp.length*100-num*10)); if ((temp.length*100-num*10) = = 0) {System.out.println (" Hope next time, thank you for participating! "); System.exit (0);}} S.close ();} /** * Letter Match * @param letters 26-Letter Save space * @param temp to save the randomly generated letters * @param flags to store whether the letter position is selected. * @param index to save randomly generated positions */private static char[] Generate () {//Letter generator char[] letters={' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '}; char[] Temp =new char[5];boolean[] flags = new Boolean[letters.length];for (int i = 0;i<temp.length;i++) {int index;do{i Ndex = (int) (Math.random () * (Letters.length));} while (Flags[index]);//Determine if the generation of letters repeats temp[i] = Letters[index];flags[index] = true;} return temp;} /** * Letter Match * @param input user guesses the letter data * @param the letter generated by the Temp letter generator * @param result is used to save the judgment result */private static int[] Check (char [] temp, char[] input) {//Letter match int[] result = new Int[2];for (int i = 0;i < input.length;i++) {for (int j=0;j < TEMP . length;j++) {if (input[I] = = Temp[j]) {//Determine if the user entered the letter correctly result[1]++; if (i==j) {//To determine if the correct letter entered by the user is in the correct position Result[0]++;break;}}}} return result;}}

  

Introduction to Java Packaging Ideas (crossword puzzle 2.0)

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.