Java cafe (6)-write a guess digital game

Source: Internet
Author: User

The last time we explained the basics of the Java language, which is limited in length and only contains a limited amount of Java syntax knowledge. In this issue, we will compile a game to guess the number based on the above back, to further learn the basic knowledge of the Java language. Guess digital games

You must have played a guess digital game-the game randomly gives a number between 0 and 99 (including 0 and 99) and then lets you guess what number it is. You can just guess a number and the game will prompt whether it is too large or too small to narrow down the result range. After several guesses and prompts, the answer is finally provided (we provide the complete code and click here to download it ). (See Figure 1)

Game Design

First, build a Java program framework. Open Eclipse, create a project named GuessNumberGame, and create a Java class named GuessNumber. Don't forget to add the appropriate javadoc to GuessNumber.

Step 1: Random Number Generation

We can use the Random class provided by Java APIs to generate a Random number.

First, add the following three lines of code to the main function:

// Create a random number generator and generate an integer between 0 and 99.
Random random = new Random ();
Int number = random. nextInt (100 );

As expected, Eclipse immediately draws a red line in the error statement like a Chinese teacher and moves the mouse over the red line to see the specific error information (see figure 2 ).

  Package concept

Java APIs include rich classes that are pre-defined by Sun like Random (Class. If you forget the concept, refer to Article 4 "taste the first cup of coffee"). similar to the variable scope issue, different packages may have classes with the same name and surname. If there is no package concept, a name conflict will occur. In addition, the package can also perform security control. You can specify which classes can be called outside the package and which cannot.

The Random class is in the java. util package. You can manually enter import java at the top of the source program. util. random; statement to declare that the program will use java. the Random class in the util package, but with Eclipse, you don't have to worry about it-move the cursor to the Random with a red wavy line, then press Ctrl + Shift + M, eclipse will automatically help you complete the import. Now, save the source code and the warning disappears? I hope you will keep in mind the usage of this shortcut key. When developing a large project, even the best minds cannot remember the name of the package where each class is located. With the help of Eclipse, it's okay if you're too lazy.

  Statement Translation

The first sentence defines the Random variable of the random type (the Java language is case sensitive, so the Random and random are different ), use the new operator to generate an instance of the Random class and assign it to the random variable. Do you still remember that there is another reference type for variables during the last serialization? This is an example. The random variable is actually a reference, pointing to an instance of the Random class created using the new operator in memory. In most cases, random can be directly regarded as an instance of the Random class. You can add ". operator "to call the method of the Random class, for example, using random. nextInt (100) to obtain a random number between 0 and 99.

The second statement defines an integer variable number to save the randomly generated integer, and assigns the random number generated by random to the number variable through direct initialization.

Step 2: Standard Input and Output

Standard I/O refers to the information flow that can be used by applications. For example, an application can read data from Standard input, write data to Standard output, and send error information to Standard error ). Through input and output, applications and applications can be connected in tandem. Although standard input/output is a concept developed from UNIX, it is also widely used in Windows. If you are familiar with DOS, this concept is naturally no stranger.
Standard input is mainly used for guessing digital games. More specifically, it is the console input. Remember that we often use System. out. println for console output? Instead, System. in is required to input data from the console. It is a pure input stream, and the guess digital game mainly obtains the player's character through the console (especially Unicode characters that support multiple languages) input, we need to wrap it into a BufferedReader instance for use:

BufferedReader input = new BufferedReader(
new InputStreamReader(System.in));

In this case, input is a BufferedReader instance that can process input from the console, support Unicode, and read the entire row. For example, input can be used. the readLine () method gets a full line of input from the player in the console.

Step 3: Exceptions

As a famous saying from argan-Shit happens, the golden rule in the program is-it will definitely make mistakes. Errors are not terrible. The key is how to handle errors.

Java provides an Exception handling mechanism to help programmers discover and handle exceptions. What is an exception? An exception is an event that can interfere with the normal process of a program during execution. There are many causes of exceptions, such as file not found, array out-of-bounds, and division by zero. When an exception occurs, an exception object is automatically generated and passed to the Java "runtime system". Specifically, an exception is thrown. The exception object contains the exception type, program running status, and other information. When the "runtime environment" gets an exception object, it interrupts the normal process of the program and automatically finds a code block that specifically handles the exception to solve the problem. Such a code block is called an Exception Handler ). You can try to fix, retry, or report an error in the exception handle, or break yourself when you cannot proceed. If the exception handle cannot be found in the "runtime environment", the Java program will be interrupted on its own.

A typical exception handling is like this:

try {
statement(s);
} catch (exceptiontype1 name) {
statement(s);
} catch (exceptiontype2 name) {
statement(s);
} finally {
statement(s);
}

Where:

★A try statement may throw an exception. A try statement must contain at least one catch or finally statement. It cannot be used independently.
★The catch statement must be used with a try statement to handle different exceptions based on the exception type. That is to say, Java has many predefined exceptions. You can use multiple catch statements to handle them in different categories. You can also define the exception type. If no exception is thrown in the try statement block, it will not be executed here.
★The finally statement must also be used with a try statement. Unlike the catch statement, the finally included statement block is executed no matter whether an exception is thrown in the try statement block.
Let's take a specific example to familiarize yourself with it. To guess a digital game, you need to obtain the number entered by the player from the console. First, we define an integer variable:int guess;

Then you can write the following code:

guess = Integer.parseInt(input.readLine());

Read the input from the console using input. readLine, convert the obtained string type input to an Integer using Integer. parseInt, and then assign it to the guess variable.

Eclipse shows you again -- the input. readLine () is marked with a red line (see Figure 3 ).

Look at the prompt. It turns out to be an unhandled exception handle.

It turns out that there is a kind of exception in Java called Checked Exceptions ). Generally, array out-of-bounds, Division by zero, and so on are all runtime exceptions. Due to the large number of such exceptions, Java allows you Not to capture them yourself, but to assign them to the runtime environment for processing. But the check type exception is different. Java raises the check type exception to the same height as the parameter and return value. That is to say, you cannot handle the check type exception, and must be commented out in javadoc.

So how can we quickly catch such exceptions? As shown in 3, click the light bulb with a Red Cross and select Surround with Try/Catch in the pop-up menu. The exception handling code module is automatically generated immediately. It can be found that this sentence will throw two exceptions: one is a format exception (NumberFormatException), because if you use Integer. parseInt to convert a Chinese character, it is naturally impossible. The other is an I/O exception, that is, the standard input may encounter unexpected problems. How can we automatically capture exceptions? This is the charm of Eclipse!

It should be noted that NumberFormatException is not a checktype exception, but a runtime exception that does not need to be captured intentionally. Try to delete all catch statement blocks that capture NumberFormatException, and Eclipse will not report an error. However, capturing this exception is very useful, and the subsequent code will further demonstrate its role.

  Tips

Benefits of using the exception Mechanism

★Makes the program more robust and the interface more friendly.
★Separating the business logic of the program from error handling makes the code more reasonable and more beautiful.
★Exceptions can be processed hierarchically to make the code more concise.
★Exceptions of the same type can be processed together to facilitate processing.

The exception handling mechanism of Java is a big topic. It only shows the tip of the iceberg. It is mainly practical. I hope you can read the extended knowledge on your own and pay attention to it when writing code.

While Loop Control

The previous Java cafe introduced the for loop statement. This time, we need to introduce its "relatient" Statement-while statement.

The syntax of the while statement is:

while ( expression ) {
statement(s)
}

First, the while statement determines that a Boolean expression is returned. If the returned value is true, the following statement is executed, and then the expression is tested and then the statement is executed, until expression returns false.

The do-while statement is very similar to the while statement. Syntax:

do {
statement(s)
} while ( expression );

Unlike the while statement that determines the true value of the expression at the top of the loop, the do-while statement determines at the bottom,

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.