Indianapolis, Indiana 46240 -...

Click here to load reader

  • date post

    31-Jan-2018
  • Category

    Documents

  • view

    219
  • download

    1

Embed Size (px)

Transcript of Indianapolis, Indiana 46240 -...

  • http://www.facebook.com/share.php?u=http://www.quepublishing.com/title/9780789753601http://twitter.com/?status=RT: download a free sample chapter http://www.quepublishing.com/title/9780789753601https://plusone.google.com/share?url=http://www.quepublishing.com/title/9780789753601http://www.linkedin.com/shareArticle?mini=true&url=http://www.quepublishing.com/title/9780789753601http://www.stumbleupon.com/submit?url=http://www.quepublishing.com/title/9780789753601/Free-Sample-Chapter

  • 800 East 96th Street, Indianapolis, Indiana 46240

    Minecraft Mods Programming

    Rogers Cadenhead

  • Minecraft Mods Programming Absolute Beginners GuideCopyright 2015 by Pearson Education, Inc.

    All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.

    ISBN-13: 978-0-7897-5360-1ISBN-10: 0-7897-5360-X

    Library of Congress Control Number: 2014953021

    Printed in the United States of America

    First Printing: November 2014

    TrademarksAll terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Que Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

    Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an as is basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

    Special SalesFor information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at [email protected] or (800) 382-3419.

    For government sales inquiries, please contact [email protected]

    For questions about sales outside the U.S., please contact [email protected]

    Acquisitions EditorMark Taber

    Managing EditorSandra Schroeder

    Senior Project Editor Tonya Simpson

    Copy EditorMegan Wade-Taxter

    Indexer Heather McNeill

    ProofreaderKathy Ruiz

    Technical EditorBoris Minkin

    Publishing CoordinatorVanessa Evans

    Cover DesignerMatt Coleman

    Compositor Mary Sudul

  • Contents at a Glance

    Part I Java from the Ground Up

    1 Dig Into Minecraft Programming with Java ............................................ 12 Use NetBeans for Minecraft Programming ...........................................153 Create a Minecraft Mod ..........................................................................254 Start Writing Java Programs ...................................................................375 Understand How Java Programs Work ..................................................516 Store and Change Information in a Mod ..............................................637 Use Strings to Communicate ..................................................................798 Use Conditional Tests to Make Decisions .............................................919 Repeat an Action with Loops ................................................................10710 Store Information with Arrays ...............................................................119

    Part II The World of Java Objects

    11 Create Your First Object .......................................................................13112 Describe What Your Object Is Like ......................................................14713 Make the Most of Existing Objects ......................................................16314 Store Objects in Data Structures ..........................................................17715 Handle Errors in a Mod .........................................................................18916 Create a Threaded Mod ........................................................................20517 Read and Write Files ..............................................................................223

    Part III Create Killer Minecraft Mods

    18 Spawn a Mob..........................................................................................24119 Make One Mob Ride Another ..............................................................25720 Take a Census of Mobs and Villages ...................................................26721 Transmute Materials in an Inventory ....................................................28122 Dig a Giant Hole ...................................................................................29323 Chop Down a Forest of Trees ..............................................................30724 Respond to Events in the Game ..........................................................32125 Display a Mobs Health During Combat .............................................33526 Make a World Change Over Time .......................................................34927 Befriend the God of Lightning .............................................................359A Visit This Books Website ......................................................................371Index ..........................................................................................................373

  • iv

    Table of Contents

    I Java from the Ground Up

    1 Dig Into Minecraft Programming with Java .......................................................1

    Setting Up a Minecraft Server .................................................................................. 2Fixing Problems Running the Server .................................................................. 5

    Connecting to the Server ......................................................................................... 9Fixing a Server Connection Problem ...............................................................10

    2 Use NetBeans for Minecraft Programming .......................................................15

    Installing NetBeans .................................................................................................16

    Creating a New Project...........................................................................................16

    Creating a New Java Class .....................................................................................18

    Running the Application .........................................................................................21

    Fixing Errors .............................................................................................................22

    3 Create a Minecraft Mod .......................................................................................25

    Creating Your First Mod .........................................................................................26

    4 Start Writing Java Programs................................................................................37

    What You Need to Write Programs ......................................................................38

    Creating the Splash Program .................................................................................38

    Beginning the Program ...........................................................................................40The class Statement ...........................................................................................42What the main Statement Does .......................................................................42Those Squiggly Bracket Marks ..........................................................................43

    Storing Information in a Variable ...........................................................................44Displaying the Contents of a Variable .............................................................44

    Saving the Finished Product ..................................................................................45

    Compiling the Program into a Class File ..............................................................46

    Fixing Errors .............................................................................................................46

  • v

    Running a Java Program .........................................................................................48Blank Spaces and Whitespace in a Java Program ..........................................49

    5 Understand How Java Programs Work .............................................................51

    Creating an Application ..........................................................................................52

    Sending Arguments to Applications .....................................................................54

    The Java Class Library.............................................................................................56

    6 Store and Change Information in a Mod ..........................................................63

    Statements and Expressions ..................................................................................64

    Assigning Variable Types .......................................................................................64Integers and Floating-Point Numbers ..............................................................65Characters and Strings .......................................................................................65Other Numeric Variable Types .........................................................................67The boolean Variable Type ...............................................................................68

    Naming Your Variables ...........................................................................................69

    Storing Information in Variables ............................................................................70

    All About Operators ................................................................................................71Incrementing and Decrementing a Variable ...................................................72Operator Precedence ........................................................................................74

    Using Expressions ....................................................................................................75

    7 Use Strings to Communicate ...............................................................................79

    Storing Text in Strings.............................................................................................80

    Displaying Strings in Programs ..............................................................................80

    Using Special Characters in Strings .......................................................................81

    Pasting Strings Together ........................................................................................82

    Using Other Variables with Strings ........................................................................83

    Advanced String Handling .....................................................................................84Comparing Two Strings .....................................................................................84Determining the Length of a String .................................................................85Changing a Strings Case ..................................................................................85Looking for a String............................................................................................86

    Presenting Credits ...................................................................................................87

  • vi

    8 Use Conditional Tests to Make Decisions .........................................................91

    if Statements ............................................................................................................92Less-Than and Greater-Than Comparisons .....................................................92Equal and Not Equal Comparisons ..................................................................93Organizing a Program with Block Statements ................................................94

    if-else Statements ....................................................................................................96

    switch Statements ....................................................................................................97

    The Ternary Operator .............................................................................................99

    Watching the Clock ...............................................................................................100

    9 Repeat an Action with Loops ........................................................................... 107

    for Loops ................................................................................................................108

    while Loops ............................................................................................................111

    do-while Loops ......................................................................................................112

    Exiting a Loop ........................................................................................................113

    Naming a Loop ......................................................................................................114Complex for Loops...........................................................................................115

    Testing Your Computer Speed ............................................................................116

    10 Store Information with Arrays .......................................................................... 119

    Creating Arrays ......................................................................................................120

    Using Arrays ...........................................................................................................121

    Multidimensional Arrays .......................................................................................124

    Sorting an Array .....................................................................................................125

    Counting Characters in Strings ............................................................................127

    II The World of Java Objects

    11 Create Your First Object ................................................................................... 131

    How Object-Oriented Programming Works .......................................................132

    Objects in Action ...................................................................................................132

    What Objects Are ..................................................................................................133

    Understanding Inheritance ...................................................................................135

  • vii

    Building an Inheritance Hierarchy ........................................................................135

    Converting Objects and Simple Variables ..........................................................136Casting Simple Variables .................................................................................137Casting Objects ................................................................................................138Converting Simple Variables to Objects and Back .......................................139Autoboxing and Unboxing ..............................................................................141

    Creating an Object ................................................................................................142

    12 Describe What Your Object Is Like ................................................................. 147

    Creating Variables .................................................................................................148

    Creating Class Variables .......................................................................................150

    Creating Behavior with Methods .........................................................................151Declaring a Method .........................................................................................151Similar Methods with Different Arguments ...................................................153Constructor Methods .......................................................................................154Class Methods ..................................................................................................155Variable Scope Within Methods .....................................................................155

    Putting One Class Inside Another .......................................................................157

    Using the this Keyword .........................................................................................158

    Using Class Methods and Variables ....................................................................159

    13 Make the Most of Existing Objects ................................................................. 163

    The Power of Inheritance ......................................................................................164Inheriting Behavior and Attributes .................................................................165Overriding Methods .........................................................................................165

    Establishing Inheritance ........................................................................................165Using this and super in a Subclass .................................................................166

    Working with Existing Objects .............................................................................167

    Storing Objects of the Same Class in Array Lists ...............................................168Looping Through an Array List .......................................................................170

    Creating a Subclass ...............................................................................................172

    14 Store Objects in Data Structures ..................................................................... 177

    Array Lists ...............................................................................................................178

    Hash Maps ..............................................................................................................184Why Classes Are Synchronized .......................................................................188

  • viii

    15 Handle Errors in a Mod ..................................................................................... 189

    Exceptions ..............................................................................................................190Catching Exceptions in a try-catch Block ......................................................191Catching Several Different Exceptions ..........................................................194Handling Something After an Exception .......................................................196Throwing Exceptions ........................................................................................197Ignoring Exceptions .........................................................................................199Exceptions That Dont Need Catch ...............................................................200

    Throwing and Catching Exceptions ....................................................................201

    16 Create a Threaded Mod .................................................................................... 205

    Threads ...................................................................................................................206Slowing Down a Program ................................................................................206Creating a Thread ............................................................................................207

    Working with Threads ...........................................................................................211The class Declaration .......................................................................................212Setting Up Variables ........................................................................................212

    The Constructor .....................................................................................................213

    Catching Errors as You Set Up URLs ...................................................................213

    Starting the Thread ...............................................................................................214Running the Thread .........................................................................................215

    Handling Mouse Clicks .........................................................................................216

    Displaying Revolving Links ...................................................................................217Stopping a Thread ...........................................................................................220

    17 Read and Write Files .......................................................................................... 223

    Streams ...................................................................................................................224Files ....................................................................................................................225Reading Data from a Stream...........................................................................226Buffered Input Streams ....................................................................................229

    Writing Data to a Stream ......................................................................................232

    Reading and Writing Configuration Properties ..................................................235

  • ix

    III Create Killer Minecraft Mods

    18 Spawn a Mob ....................................................................................................... 241

    The Mod Framework .............................................................................................242

    Starting a Mod Project ..........................................................................................245

    Writing the Mods Code .......................................................................................248Deploying a Mod .............................................................................................254

    19 Make One Mob Ride Another .......................................................................... 257

    Starting the Project ...............................................................................................258

    Writing the Mod ....................................................................................................259

    Deploying the Mod ...............................................................................................264

    20 Take a Census of Mobs and Villages............................................................... 267

    Starting the Project ...............................................................................................268

    Creating the Project ............................................................................................269Deploying a Mod .............................................................................................278

    21 Transmute Materials in an Inventory ............................................................... 281

    Starting the Project ...............................................................................................282

    Creating the Project ..............................................................................................284Deploying the Mod ..........................................................................................289

    22 Dig a Giant Hole ................................................................................................. 293

    Starting the Project ...............................................................................................294

    Creating the Project ..............................................................................................295Deploying the Mod ..........................................................................................301Backing Up a Minecraft World ........................................................................302

    23 Chop Down a Forest of Trees .......................................................................... 307

    Starting the Project ...............................................................................................308

    Creating the Project ..............................................................................................309Deploying the Mod ..........................................................................................318

    24 Respond to Events in the Game ...................................................................... 321

    Starting the Project ...............................................................................................322

    Creating the Project ..............................................................................................323Deploying the Mod ..........................................................................................331

  • x

    25 Display a Mobs Health During Combat ......................................................... 335

    Starting the Project ...............................................................................................336

    Creating the Project ..............................................................................................338Deploying the Mod ..........................................................................................345Learning Bukkit Methods from NetBeans ......................................................346

    26 Make a World Change Over Time ................................................................... 349

    Starting the Project ...............................................................................................350

    Creating the Project ..............................................................................................351Deploying the Mod ..........................................................................................357

    27 Befriend the God of Lightning ......................................................................... 359

    Starting the Project ...............................................................................................360

    Stepping Through Mod Development ................................................................360

    Creating the Project ..............................................................................................361Deploying the Mod ..........................................................................................366Joining the Community of Mod Developers .................................................367

    A Visit This Books Website .................................................................................. 371

    Index ............................................................................................................................. 373

  • ABOUT THE AUTHOR xi

    About the AuthorRogers Cadenhead is a writer, computer programmer, and web developer who has written more than 20 books on Internet-related topics, including Sams Teach Yourself Java in 24 Hours. He maintains the Drudge Retort and other websites that receive more than 20 million visits a year. This books official website is at www.javaminecraft.com.

    DedicationThis book is dedicated to the kids out there who have been inspired by Minecraft to learn computer programming, whether theyre 10, 20, or 50. There are a lot of great experiences ahead of you, not only in writing mods for a video game but in what you do with your skills beyond the game world.

    AcknowledgmentsTo the folks at Pearson, especially Mark Taber, Tonya Simpson, Boris Minkin, and Megan Wade-Taxter. No author can produce a book like this on his own. Their excellent work will give me plenty to take credit for later.

    To my wife, Mary, and my sons, Max, Eli, and Sam.

    http://www.javaminecraft.com

  • xii MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    We Want to Hear from You!As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what were doing right, what we could do better, what areas youd like to see us publish in, and any other words of wisdom youre willing to pass our way.

    We welcome your comments. You can email or write to let us know what you did or didnt like about this bookas well as what we can do to make our books better.

    Please note that we cannot help you with technical problems related to the topic of this book.

    When you write, please be sure to include this books title and author as well as your name and email address. We will carefully review your comments and share them with the author and editors who worked on the book.

    Email: [email protected]

    Mail: Que Publishing ATTN: Reader Feedback800 East 96th StreetIndianapolis, IN 46240 USA

    Reader ServicesVisit our website and register this book at quepublishing.com/register for convenient access to any updates, downloads, or errata that might be available for this book.

  • This page intentionally left blank

  • I N T H I S C H A P T E R

    4 Type a Java program into a source code editor

    Organize a program with bracket marks

    Store information in a variable

    Display the information stored in a variable

    Save, compile, and run a program

    START WRITING JAVA PROGRAMSA computer program is a set of instructions that tells a computer what

    to do. These instructions are given to a computer using a programming

    language.

    During this chapter, you create a simple program with the Java language

    by entering it into a text editor. When thats done, you save the program,

    compile it, and test it. Then you break it on purpose and fix it again, just

    to show off.

  • 38 MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    What You Need to Write ProgramsTo create Minecraft mods or any other Java programs, you must have a programming tool that supports the Java Development Kit (JDK) such as the NetBeans integrated development environment (IDE). You need a tool that can compile and run Java programs and a text editor to write those programs.

    With most programming languages, computer programs are written by entering text into a text editor (also called a source code editor). Some programming languages come with their own editor. NetBeans includes its own editor for writing Java programs.

    Java programs are simple text files without any special formatting, such as centered text or boldface text. The NetBeans source code editor functions like a simple text editor with some extremely useful enhancements for programmers. Text turns different colors as you type to identify different elements of the language. NetBeans also indents lines properly and provides helpful programming documentation inside the editor.

    Because Java programs are text files, you can open and edit them with any text editor. You could write a Java program with NetBeans, open it in Notepad or Text Edit and make changes, and then open it again later in NetBeans without any problems.

    Creating the Splash ProgramOne of the funny quirks of Minecraft is the random message that displays in the game client when the program is run. It appears as yellow text across a corner of the Minecraft logo, as shown in Figure 4.1.

  • CHAPTER 4START WRITING JAVA PROGRAMS 39

    FIGURE 4.1

    The Minecraft client displaying a splash message.

    The splash in Figure 4.1 is Dont feed avocados to parrots! Mojang, the devel-oper of Minecraft, uses the splash to crack jokes, make references to classic or obscure videogames, and say other unusual things. Sometimes it even dispenses good advice, as in this particular example. Avocados are poisonous to birds and harmful to many other animals.

    The first Java program that you create will have its own simple splash message: Blue warrior shot the food!

    To prepare for the first programming project in NetBeans, if you havent already done so, create a new project called Minecraft by following these steps:

    1. Select the menu command File, New Project. The New Project dialog opens.

    2. Select the project category Java and the project type Java Application; then click Next.

    3. Enter Minecraft as the projects name. (If you created a project with this name previously, you see the error message Project folder already exists and is not empty.)

    4. Deselect the Create Main Class check box.

    5. Click Finish.

  • 40 MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    The Minecraft project is created in its own folder. You can use this project for the Java programs you write as you progress through this bookat least as far as Chapter 17, Read and Write Files. After that, you will be creating each Minecraft mod as its own project in NetBeans.

    Beginning the ProgramNetBeans groups related programs together into a project. If you dont have the Minecraft project open, heres how to retrieve it:

    1. Select File, Open Project. A file dialog appears.

    2. Find and select the folder where you installed the Bukkit server (if necessary).

    3. Open that folder.

    4. Select Minecraft and click Open Project.

    The Minecraft project appears in the Projects pane next to a coffee cup icon and a + sign that can be expanded to see the files and folders the project contains.

    To add a new Java program to the currently open project, select File, New File. The New File Wizard opens, as shown in Figure 4.2.

    FIGURE 4.2

    The New File Wizard.

  • CHAPTER 4START WRITING JAVA PROGRAMS 41

    The Categories pane lists the different kinds of Java programs you can create. Click the Java folder in this pane to see the file types that belong to this category. For this first project, select the Empty Java File type and click Next.

    A New Empty Java File dialog opens. Follow these steps to begin writing the program:

    1. In the Class Name field, enter Splash.

    2. In the Package field, enter com.javaminecraft.

    3. Click Finish.

    So you can begin working right away on your program, an empty file named Splash.java opens in the source code editor. Using the editor, begin your Java programming career by entering each line from Listing 4.1. These statements are called the programs source code.

    CAUTION As you were warned in an earlier chapter, dont enter the line number and colon at the beginning of each linethese are used in this book to reference specific line numbers.

    LISTING 4.1 The Splash Program

    1: package com.javaminecraft;

    2:

    3: class Splash {

    4: public static void main(String[] arguments) {

    5: // My first Java program goes here

    6: }

    7: }

    Be sure to capitalize everything exactly as shown, and use your spacebar or Tab key to insert the blank spaces in front of Lines 46. When youre done, select File, Save to save the file.

    At this point, Splash.java contains the bare-bones form of a Java program.

    You will create many programs that start exactly like this one, except for the word Splash on Line 3. This word represents the name of your program and changes with each program you write. Line 5 should make sense to you because its a sentence in actual English. The rest is probably new to you, aside from the sample Minecraft mod you wrote and tested in Chapter 3, Create a Minecraft Mod.

  • 42 MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    The class StatementThe first line of the program is the following:package com.javaminecraft;

    A package is a way to group Java programs together. This line tells the computer to make com.javaminecraft the package name of the program.

    After a blank line, the third line is this:class Splash {

    Translated into English, it means, Computer, give my Java program the name Splash.

    As you might recall from Chapter 3, each instruction you give a computer is called a statement. The class keyword is the way you give your computer program a name. Its also used to determine other things about the program, as you will see later. The significance of the term class is that Java programs also are called classes.

    In this example, the program name Splash matches the documents filename, Splash.java. A Java program must have a name that matches the first part of its filename and should be capitalized the same way.

    If the program name doesnt match the filename, you get an error when you try to compile some Java programs, depending on how the class statement is being used to configure the program.

    What the main Statement DoesThe next line of the program is the following:public static void main(String[] arguments) {

    This line tells the computer, The main part of the program begins here. Java programs are organized into different sections, so there needs to be a way to identify the part of a program that is executed first when the program is run.

    The main statement is the entry point to most Java programs. Mods are an exception because they are run by the Bukkit server and cannot be run directly. When a player types a command that a mod supports, the server runs that mod.

    Some other exceptions are applets, programs that are run on a web page by a web browser; servlets, programs run by a web server; and apps, programs run by a mobile device.

    The Java programs you write during the next 13 chapters use main as their starting point. Thats because you run them directly on your computer. Mods, applets, apps, and servlets are run indirectly by another program or device.

  • CHAPTER 4START WRITING JAVA PROGRAMS 43

    To differentiate programs with main from these other types, they are called applications.

    Those Squiggly Bracket MarksIn the Splash program, Lines 3, 4, 6, and 7 contain a squiggly bracket mark of some kindeither a { or a }. These brackets are a way to group lines of your program (in the same way that parentheses are used in a sentence to group words). Everything between the opening bracket { and the closing bracket } is part of the same group.

    These groupings are called blocks. In Listing 4.1, the opening bracket on Line 3 is associated with the closing bracket on Line 7, which makes your entire program a block. You use brackets in this way to show the beginning and end of a program.

    Blocks can be located inside other blocks (just as parentheses are used in this sentence (and a second set is used here)). The Splash program has brackets on Line 4 and Line 6 that establish another block. This block begins with the main statement. The lines inside the main statements block will be run when the program begins.

    TIP NetBeans can help you figure out where a block begins and ends. Click one of the brackets in the source code of the Splash program. The bracket you clicked turns yellow along with its corresponding bracket. The Java statements enclosed within the two yellow brackets are a block. This tip is not that useful on a short program like Splash, but as you write much longer programs, it helps you avoid looking like a blockhead.

    The following statement is the only thing located inside the block:// My first Java program goes here

    This line is a placeholder. The // at the beginning of the line tells the computer to ignore this line because it was put in the program solely for the benefit of humans who are looking at the source code. Lines that serve this purpose are called comments.

    Right now, you have written a complete Java program. It can be compiled, but if you run it, nothing happens. The reason is that you havent told the computer to do anything yet. The main statement block contains only a single comment, which is ignored by the computer. You must add some statements inside the opening and closing brackets of the main block.

  • 44 MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    NOTE Semicolons are required at the end of each Java statement, but in the Splash program the line // My first Java program goes here does not end with a semicolon.

    The reason this is permitted is because comments are completely ignored by the compiler. If you put // on a line in your program, this tells the Java compiler to ignore everything to the right of the // on that line. The following example shows a comment on the same line as a statement:

    System.out.println(greeting); // Exploding creepers!

    Storing Information in a VariableIn the programs you write, you need a place to store information for a brief period of time. You can do this by using a variable, a storage place that can hold information such as integers, floating-point numbers, true-false values, characters, and lines of text. The information stored in a variable can change, which is how it gets the name variable.

    In Splash.java file, replace Line 5 with the following:String greeting = Blue warrior shot the food!;

    This statement tells the computer to store the text Blue warrior shot the food! in a variable called greeting.

    In a Java program, you must tell the computer what type of information a variable will hold. In this program, greeting is a stringa line of text that can include letters, numbers, punctuation, and other characters. Putting String in the statement sets up the variable to hold string values.

    When you enter this statement into the program, a semicolon must be included at the end of the line. Semicolons end each statement in a Java program. Theyre like the period at the end of a sentence. The computer uses them to determine when one statement ends and the next one begins.

    Putting only one statement on each line makes a program more understandable (for us humans).

    Displaying the Contents of a VariableIf you run the program at this point, it still seems like nothing happens. The command to store text in the greeting variable occurs behind the scenes. To make the computer show that it is doing something, you can display the contents of that variable.

  • CHAPTER 4START WRITING JAVA PROGRAMS 45

    Insert another blank line in the Splash program after the String greeting = Blue warrior shot the food! statement. Use that empty space to enter the following statement:System.out.println(greeting);

    This statement tells the computer to display the value stored in the greeting variable. The System.out.println statement makes the computer display information on the system output deviceyour monitor.

    Now youre getting somewhere.

    Saving the Finished ProductYour program should now resemble Listing 4.2, although you might have used slightly different spacing in Lines 56. Make any corrections that are needed and save the file (by selecting the menu command File, Save).

    LISTING 4.2 The Finished Version of the Splash Program

    1: package com.javaminecraft;

    2:

    3: class Splash {

    4: public static void main(String[] arguments) {

    5: String greeting = Blue warrior shot the food!;

    6: System.out.println(greeting);

    7: }

    8: }

    When the computer runs this program, it runs each of the statements in the main statement block on Lines 5 and 6. Listing 4.3 shows what the program would look like if it was written in the English language instead of Java.

    LISTING 4.3 A Line-by-Line Breakdown of the Splash Program

    1: Put this program in the com.javaminecraft package.

    2:

    3: The Splash program begins here:

    4: The main part of the program begins here:

    5: Store the text Blue warrior shot the food! in a String named greeting

  • 46 MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    6: Display the contents of the variable greeting

    7: The main part of the program ends here.

    8: The Splash program ends here.

    Compiling the Program into a Class FileBefore you can run a Java program, you must compile it. When you compile a program, the instructions given to the computer in the program are converted into a form the computer can better understand.

    NetBeans compiles programs automatically as they are saved. If you typed everything as shown in Listing 4.2, the program compiles successfully.

    A compiled version of the program, a new file called Splash.class, is created. All Java programs are compiled into class files, which are given the .class file extension. A Java program can be made up of several classes that work together, but in a simple program such as Splash only one class is needed.

    The compiler turns Java source code into bytecode, a form that can be run by a Java Virtual Machine (JVM).

    NOTE The Java compiler speaks up only when theres an error to complain about. If you compile a program successfully without any errors, nothing happens in response. This is disappointing. When I was starting out as a Java programmer, I was hoping successful compilation would be met with a grand flourish of celebratory horns.

    Fixing ErrorsAs you compose a program in the NetBeans source editor, errors are flagged with a red alert icon to the left of the editor pane, as shown in Figure 4.3.

  • CHAPTER 4START WRITING JAVA PROGRAMS 47

    Error Icon

    FIGURE 4.3

    Spotting errors in the source editor.

    The icon appears on the line that triggered the error. You can click this icon to display an error message that explains the compiler error with these details:

    The name of the Java program

    The type of error

    The line where the error was found

    Heres an example of an error message you might see when compiling the Splash program:cannot find symbol.

    symbol : variable greting

    location: class Splash

    The error is the first line of the message: cannot find symbol. These messages often can be confusing to new programmers. When the error message doesnt make sense to you, dont spend much time trying to figure it out. Instead, take a look at the line where the error occurred and look for the most obvious causes.

    For instance, can you determine whats wrong with the following statement?System.out.println(greting);

  • 48 MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    The error is a typo in the variable name, which should be greeting instead of greting. (Add this typo on purpose in NetBeans to see what happens.)

    If you get error messages when creating the Splash program, double-check that your program matches Listing 4.2 and correct any differences you find. Make sure that everything is capitalized correctly and all punctuation marks such as {, }, and ; are included.

    Often, a close look at the line identified by the error message is enough to reveal the error (or errors) that needs to be fixed.

    Take note that the line number displayed with the error message isnt always the place where an error needs to be fixed. Examine the statements that are directly above the error message to see whether you can spot any typos or other bugs. The error usually is within the same programming block.

    TIP This books official website at www.javaminecraft.com includes source files for all programs you create. If you cant find any typos or other reasons for errors in the Splash program but there are still errors, go to the books website and download Splash.java from the Chapter 4 page. Try to run that file instead.

    Running a Java ProgramTo see whether the Splash program does what you want, run the class with the JVM, the interpreter that runs all Java code. In NetBeans, select the menu command Run, Run File. An Output pane opens below the source code editor. In this pane, if there are no errors, the program displays the output, as shown in Figure 4.4.

    http://www.javaminecraft.com

  • CHAPTER 4START WRITING JAVA PROGRAMS 49

    Output Pane

    FIGURE 4.4

    Running the Splash Java program.

    If you see the text Blue warrior shot the food!, you have written, compiled, and run the Java program successfully.

    NOTE The message Blue warrior shot the food! is a splash message in Minecraft that pays homage to Gauntlet, a 1980s coin-operated videogame in which up to four players roamed through a dungeon killing monsters and accumulating treasure. Because players needed food to stay alive, accidentally shooting the food was a major faux pas.

    You can find all of Minecrafts known splash messages and expla-nations for many of them on Minecraft Wiki. Visit the web page at http://minecraft.gamepedia.com/Splash.

    Blank Spaces and Whitespace in a Java ProgramAs you typed in the Splash program in Listing 4.1, taking care to get the right number of spaces before each statement to make sure it all lined up properly, you might have asked yourself whether thats important.

    Blank spaces and whitespace are completely unimportant as far as the computer is concerned. Spacing is strictly for the benefit of people looking at a computer

    http://minecraft.gamepedia.com/Splash

  • 50 MINECRAFT MODS PROGRAMMING ABSOLUTE BEGINNERS GUIDE

    programthe Java compiler doesnt care. You could have written the Splash program without using blank spaces or used the Tab key to indent lines, and it would compile successfully.

    Although the number of spaces in front of lines isnt important, you should use consistent spacing and indentation in your Java programs. Why? Because spacing makes it easier for you to see how a program is organized and to which programming block a statement belongs.

    The programs you write must be understandable to other programmers, including yourself when you look at the code weeks or months later to fix a bug or make an enhancement. Consistency in spacing and indentation are part of whats called a programming style. Good programmers adopt a style and practice it in all their work.

    THE ABSOLUTE MINIMUMDuring this chapter, you got an introduction to all the elements of a Java program. You learned that to develop a program you need to complete these three basic steps:

    1. Write the program with a text editor or a tool such as NetBeans.

    2. Compile the program into a class file.

    3. Tell the Java Virtual Machine to run the class.

    Along the way, you were introduced to some basic computer programming concepts such as compilers, interpreters, blocks, statements, and variables. These will become clearer to you in successive chapters. As long as you got the Splash program to work during this chapter, youre ready to proceed.

  • Symbols(\\) (backslashes), 82, 225$ (dollar sign), 69{} (curly brackets), 64

    arrays, 121Java programs, 43

    -- (decrement operator), 72/ (division operator), 72 (double quotation marks), 66,

    81// (double slashes), 43= (equal signs), 66, 70== (equality operator), 93/ (forward slashes), 225> (greater than operator), 92++ (increment operator), 72!= (inequality operator), 94< (less than operator), 92- (minus sign), 72* (multiplication operator), 72% operator, 72+= operator, 84+ (plus sign)

    addition operator (+), 72concatenation operator,

    82-83increment operator (++), 72

    ? (question mark), 99-100; (semicolons), 44, 115 (single quotation marks), 66, 82[ ] (square brackets), 120, 284_ (underscores)

    large numbers, 67variable names, 69

    Aaccess control

    defined, 148methods, 152variables, 149

    accessor methods, 153ActionListener interface, 212

    actionPerformed() method, 216add() method, 165, 169, 178addition operator (+), 72addPotionEffect() method, 264adjacent blocks, retrieving, 327alert() method, 153AnimatedLogo class, 166annotations

    @EventHandler, [email protected], 324

    Apache Project class libraries, 57applechicken command, 351applets, 51applications, 51

    argumentspassing, 54storing, 56

    Battlepoint, 181-183Benchmark, 116-117Calculator, 191-193Clock, 100-104ClockTalk, 104Command, 54-55Commodity, 98-99Configurator, 237-238ConfigWriter, 233-235Console, 230-231CreditCardChecker, 198Credits, 87-88defined, 43, 51Dice, 58-59FindPrimes, 208-211FontMapper, 186-187Game, 94-95HomePage, 201-202ID3Reader, 227-229LinkRotator

    class declaration, 212constructors, 213error handling, 213-214mouse clicks,

    handling, 216revolving links,

    displaying, 217-219running threads, 215-216starting, 214stopping threads, 220

    variables, setting up, 212-213

    NameSorter, 125-126NewCalculator, 193-194NewRoot, 140-141Nines, 109-110NumberDivider, 195-196organizing, 94-96PageCatalog, 202-203PlanetWeight, 76-78PointTester, 172-176Root, 52-53running, 21SpaceRemover, 123-124Spartacus, 20-23StringLister, 170-171Variable, 65-66Virus, 153-155, 159VirusLab, 160-161Wheel of Fortune, 127-130

    arguments[ ] (square brackets), 284onCommand() method, 243passing

    applications, 54methods, 153

    PotionEffect() constructor, 264

    storing, 56Summon command, 56

    array index out of bounds errors, 122

    ArrayIndexOutOfBounds-Exception class, 190

    ArrayList class, 168-170arrays

    arguments, storing, 56character

    declaring, 122Wheel of Fortune

    application, 129declaring, 120defined, 119elements, 120-121exceptions, 122initial values, 120

    Index

  • 374 ARRAYS

    integersdeclaring, 120Wheel of Fortune

    application, 129lists

    adding objects, 169creating, 168, 178defined, 178elements, retrieving, 169generics, 178looping through, 170objects. See objects,

    array listsoutside-the-cube trees,

    310-311points, creating, 180-183size, 179vectors, compared, 179

    multidimensional, 124-125pageLink, 213pageTitle, 212-213sample application, 123-124searched locations,

    storing, 313sorting, 125-126strings, 120upper limits, 122Wheel of Fortune

    application, 127-130Arrays class, 125asterisk (*) (multiplication

    operator), 72attributes, 132

    defined, 147inheritance, 135

    autoboxing, 141

    Bbacking up worlds, 302-304backslash character (\\), 82, 225backspace special character, 82bats, summoning with

    coordinates, 56Battlepoint application, 181-183bedrock, digging, 296behaviors, 132-135Benchmark application, 116-117BestFriendOfZeus mod, 360

    Bukkit class library, adding, 360

    deploying, 366event listener, registering, 362events, receiving, 362

    lightning bolts, throwing, 363mob attack targets, 362-363mob found somebody to

    attack, retrieving, 362plug-in configuration file, 360project, creating, 360source code, 364-366

    bigdig command, 295BigDig mod

    block materials, changing, 297blocks around players,

    examining, 296Bukkit class library,

    adding, 294circles around players,

    digging out, 295-297deploying, 301hole completion sound/

    message, 297hole size, determining, 295plug-in configuration file, 294project, creating, 294source code, 298-301

    binary value variables, 68blank spaces (Java programs),

    49-50block statements, 64, 94-96BlockFace enumeration, 327blocks, 43

    adjacent, retrieving, 327around players,

    examining, 296changing ground under

    players. See StoneWalker mod

    destroying, 297getRelative() method, 327getType() method, 250materials

    changing, 297determining, 250, 310stone eligibility, 327tree saplings, planting, 353

    right below players, finding, 327

    turning into air, 297Boole, George, 69boolean variables, 68-69brackets

    { } (curly)arrays, 121Java programs, 43

    [ ] (square), 120, 284break statement, 98, 113

    breaking loops, 113browse() method, 216buffered input streams, 229-231BufferedInputStream()

    constructor, 230Bukkit

    Plugins directory website, 368Project website, 3

    Bukkit class libraryadding to projects, 245events

    documentation, 346handling methods, 326packages, 325

    Java documentation, 290, 367website, 61

    Bukkit Minecraft serverBukkit server JAR file cant be

    found error, 5connections

    creating, 9-10fixing, 11-12

    downloading, 2EULA check, 4Java virtual machine cant be

    found error, 7-9player profiles, changing, 12running first time, 4starting, 3

    bytecode, 224bytes

    reading, 226-227skipping, 227streams, 224variables, 67writing to streams, 233

    CC418, 229CableModem class, 143Calculator application, 191-193cancelling event normal

    behaviors, 352cannot find symbol error

    message, 47carriage return character, 82case

    sensitivityconsistency, 70variable names, 69

    strings, changing, 85case statements, 97

  • How can we make this index more useful? Email us at [email protected]

    COLLECTIONS 375

    casting, 136-137autoboxing, 141defined, 137destinations, 137objects, 138sources, 137unboxing, 141variables, 137

    catching exceptions, 190-191handling something after,

    196-197HomePage application,

    201-202multiple exceptions, 194PageCatalog application,

    202-203throwing exceptions,

    compared, 190try-catch blocks, 191

    Calculator application, 191-193

    NewCalculator application, 193-196

    censusmobs, 268

    Bukkit class library, adding, 268

    commands, executing, 269current mobs, listing, 269deploying, 278player messages,

    sending, 271plug-in configuration file,

    268-269project creating, 268source code, 274-277type counts, storing,

    270-273villagers

    creating, 273-274deploying, 279

    char variables, declaring, 66, 80characters

    char variables, declaring, 66declaring, 122defined, 65, 80quotation marks, 66special, 81-82streams, 224string variables, declaring, 66Wheel of Fortune

    application, 129checkAuthor() method, 158CheckDatabase class, 198chickens

    spawning, 351speed, setting, 264turning into tree laying

    mutants. See JohnnyApple-chicken mod

    zombies riding. See ZombieChicken mod

    ChickenStorm modBukkit class library,

    adding, 245chickens, spawning

    babies versus adults, 251block materials,

    determining, 250number of, 248random locations, 250specific locations, 249-250

    deploying, 254-255JAR file, finding, 253overpopulating, 249project, creating, 245source code, 251-253YAML file, 246-248

    chopAdjacentTrees() method, 312-313

    chopping down trees. See TreeChopper mod

    circle radius, calculating, 295class statement, 42, 134, 324classes, 132

    AnimatedLogo, 166Applet, 165ArrayIndexOutOfBounds-

    Exception, 190ArrayList, 168-170Arrays, 125Bukkit, 61CableModem, 143CheckDatabase, 198Console, 230-232declaring, 42, 212defined, 25, 57Double, 295DslModem, 143encapsulation, 153event listeners, 321Exception, 190file, 225FileInputStream, 232FileOutputStream, 232FileReader, 232FileWriter, 232Font, 186helper, 157hierarchy, 164-166

    HighSpeedModem, 135importing, 260-261inheritance, 135, 164-165inner, 311interfaces. See interfacesItemSpawnEvent, 352ItemStack, 281JApplet, 164-165libraries, 25-27, 245, 258LinkRotator, 212Loc, 311Logger, 244Material, 281, 284, 290Math

    documentation, 60floor() method, 58random() method, 58, 249sqrt() method, 53

    methods, declaring, 155Modem, 134, 142ModemTester, 144nesting, 157NetBeans

    automatic importing, 260-261

    compiling, 20creating, 18-21running, 21

    packages, 31PetWolf program, 31PlayerInventory, 281PlayerMoveEvent, 326Point, 172Point3D, 172-174PotionEffect, 264Properties, 235RuntimeException, 200subclasses. See subclassessuperclasses, 135synchronization, 188System, 230testing, 174Thread

    sleep() method, 206stop() method, 211

    threaded, 207, 210-211variables, 148-150Vector, 184Villager, 274Virus, 148

    Clock application, 100-104ClockTalk application, 104close() method, 224, 233closing streams, 224, 233collections, 171

  • 376 COLORS (TEXT OUTPUT)

    colors (text output), 340-341com object, creating, 134-135Command application

    creating, 54output, 55source code, 55

    commandOn variable, 351commands

    applechicken, 351bigdig, 295stonewalk, 322stopstonewalk, 322Summon, 56

    CommandSender object verification, 243

    comments, 29, 43Commodity application, 98-99comparing strings, 84, 92-93compiling

    classes, 20Java programs, 46

    complex for loops, 115computer speed, testing, 116-117concatenating strings, 82-83concatenation operator (+), 82-83conditionals, 92

    Clock application, 100-104ClockTalk application, 104defined, 91if, 92

    blocks, 94-96equal/not equal

    comparisons, 93less/greater-than

    comparisons, 92-93if-else, 96-97switch, 97-98ternary operator (?), 99-100

    configuration settings. See properties

    Configurator application, 237-238

    ConfigWriter application, 233-235

    connections (Minecraft servers)creating, 9-10fixing, 11-12

    Console application, 230-231Console class, 230-232console input, 230constants, 71constructors

    arguments, 154BufferedInputStream(), 230

    declaring, 154FileInputStream(), 226FileOutputStream(), 232inheritance, 154Location, 249PotionEffect(), 264threads, 213

    contains() method, 169containsKey() method, 186containsValue() method, 186continue statement, 113controlling access. See access

    controlconverting. See also casting

    properties to numerical values, 236

    variables to objects, 139coordinates (players),

    finding, 249counters, 108createNewFile() method, 225Creative Commons license, 229credit card purchase verification

    application, 198CreditCardChecker

    application, 198Credits application, 87-88curly brackets { }, 64

    arrays, 121Java programs, 43

    current location, retrieving, 29currentThread() method, 215

    Ddamage() method, 347data types, 44

    binary values, 68boolean, 68-69byte, 67char, 66, 80enum, 271floating-point numbers, 65hexadecimal values, 68integer, 65long, 67short, 67strings. See strings

    debugging OOP applications, 133declaring

    arrays, 120elements, 120integers, 120lists, 178

    multidimensional, 124-125strings, 120

    char variables, 80classes, 42, 212methods, 151

    classes, 155constructors, 154public methods, 152

    subclasses, 172extends statement, 165Point3D class, 172-173super statement, 167this statement, 166

    variables, 64-65, 148access control, 148-149binary values, 68boolean, 68-69byte, 67char, 66class variables, 150floating-point, 65hexadecimal values, 68integers, 65LinkRotator application,

    212-213long, 67public, 149quotation marks, 66short, 67strings, 66, 80

    decrement operator (--), 72decrementing variables, 72-74default statements, 98default variables, 149delete() method, 225deleting files, 225deploying mods, 254-255

    BestFriendOfZeus, 366BigDig, 301HealthChecker, 345JohnnyApplechicken, 357MobCensus, 278PetWolf mod, 34StoneWalker mod, 331-332Transmuter mod, 289-290TreeChopper, 318ZombieChicken, 264

    deprecated, 211Desktop object, 216destinations (casting), 137destroying blocks, 297dialogs

    New Empty Java File, 41New Project, 39

  • How can we make this index more useful? Email us at [email protected]

    EXCEPTIONS 377

    diamonds, transmuting into zombie flesh, 282

    Dice application, 58-59digging

    bedrock, 296BigDig mod

    block materials, changing, 297

    blocks around players, examining, 296

    Bukkit class library, adding, 294

    circles around players, 295-297

    deploying, 301hole completion sound/

    message, 297hole size,

    determining, 295plug-in configuration

    file, 294project, creating, 294source code, 298-301

    holes at spawn points, 319display variable, 338displaying

    credits, 87-88Java program errors, 46mob health state during battle.

    See HealthChecker modmods source code on

    GitHub, 368properties, 236revolving links, 217-219strings

    println() method, 80-81special characters, 81-82

    variable contents, 44displaySpeed() method, 134distances, calculating, 273division operator (/), 72do-while loops, 112-113dollar sign ($), 69Double class, 295double quotation marks (), 66, 81double slashes (//), 43DslModem class, 143duration, 264

    Eelements, 120-121, 169else statements, 96-97encapsulation, 153

    end-user license agreements (EULAs), 4

    endless loops, 112entities. See packagesEntityDamageEvent object, 338EntityTargetEvent object, 339EntityTargetEvent.TargetReason

    enumeration, 363entrySet() method, 186, 272enumerations, 271

    BlockFace, 327EntityTargetEvent.Target-

    Reason, 363equal sign (=), 66, 70equality, 93equals() method, 84, 165equalsIgnoreCase() method, 243errors

    arrays, 122defined, 189exceptions, 190-191

    ArrayIndexOutOf-BoundsException, 190

    catching multiple, 194-196catching with try-catch

    blocks, 191-194creating, 199defined, 189Exception class, 190handling something after,

    196-197HomePage application,

    201-202ignoring, 199-200PageCatalog application,

    202-203throwing, 197-199throwing versus

    catching, 190unchecked, 200-201

    handling, 194, 213-214IndexOutOfBounds-

    Exception, 200Java programs, 47-48MalformedURLException, 199Minecraft server

    Bukkit server JAR file cant be found error, 5

    Java virtual machine cant be found error, 7-9

    NetBeans, fixing, 22-23, 259NullPointerException, 200NumberFormatException,

    194, 197escape sequences, 81

    EULAs (end-user license agreements), 4

    @EventHandler annotation, 326events

    defined, 321documentation, 346explosions, 346handling, 321

    adjacent blocks, retrieving, 327

    block materials, transforming, 328

    blocks right below players, finding, 327

    defined, [email protected]

    annotation, 326graphical user

    interfaces, 324methods, 326mod on status,

    checking, 327player locations, 326-327registerEvents()

    method, 325lightning bolts, throwing, 363listening, 321

    mob current/maximum health, determining, 339

    mobs taking damage, 338mobs targeting players for

    attack, 339mods as listeners,

    registering, 324-325, 362StoneWalker mod, 324

    mobsattack target reasons, 363found somebody to attack,

    retrieving, 362targets, identifying, 362

    mods, receiving, 362mouse clicks, handling, 216normal behavior,

    cancelling, 352packages, 325player caused, 326

    exclamation points (mob health), calculating, 340

    Exception class, 190exceptions, 122, 190

    array index out of bounds, 122, 190

  • 378 EXCEPTIONS

    catching, 190-191multiple, 194-196try-catch blocks, 191-194versus throwing, 190

    creating, 199defined, 189Exception class, 190handling something after,

    196-197HomePage application,

    201-202ignoring, 199-200PageCatalog application,

    202-203throwing, 197-199unchecked, 200-201

    executeCommand() method, 243, 284-285

    exists() method, 225exiting loops, 113explosions, 346expressions, 75. See also

    operatorsadvantages, 76defined, 64increment/decrement

    operators, 73operator precedence, 74-75PlanetWeight application,

    76-78extends statement, 143, 165

    FFile class, 225FileInputStream class, 232FileInputStream()

    constructor, 226FileOutputStream class, 232FileOutputStream()

    constructor, 232FileReader class, 232files

    creating, 225deleting, 225existence, checking, 225File class, 225JAR. See JARsnames, 225properties, 235

    Configurator application, 237-238

    converting to numerical values, 236

    displaying all, 236loading, 236names, 235retrieving, 236storing, 236

    reading, 226ID3Reader application,

    227-229multiple bytes, 227single bytes, 226skipping bytes, 227

    renaming, 225size, finding, 225writing to, 232

    bytes, 233ConfigWriter application,

    233-235output stream,

    creating, 232write() method, 232

    YAML. See YAML filesFileWriter class, 232finding

    blocks right below players, 327

    mods, 368outside-the-cube trees,

    311-313player coordinates, 249strings, 86

    FindPrimes application, 208-211float statement, 65float variable, 65floating-point numbers

    declaring, 65rounding down, 58

    floor() method, 58folders

    contents, listing, 226creating, 225

    Font class, 186FontMapper application,

    186-187Football application, 94-95for loops, 108-109

    array lists, 170complex, 115counter variables, 108empty sections, 115exiting, 113Nines application, 109-110spawning chickens, 351syntax, 108-109

    formfeeds character, 82forward slashes (/), 225

    framework (mods), 242-245CommandSender object

    verification, 243equalsIgnoreCase()

    method, 243executeCommand()

    method, 243onCommand() method, 243player locations,

    retrieving, 244Player object, creating, 244server messages,

    logging, 244World object access, 244

    friends, creating. See BestFriend-OfZeus mod

    GGame application, 94-95gameOver variable, 69Gauntlet, 49generics, 178get() method

    array lists, 169hash maps, 185

    getAmount() method, 286getBlock() method, 250, 327getBytes() method, 233getEntity() method

    BestFriendOfZeus mod, 362mob damage, 338

    getFrom() method, 327getHealth() method, 339getIdentifier() method, 153getInventory() method, 285getItem() method, 286getKey() method, 272getLivingEntities() method, 269getLocation() method, 29, 244getMaterial() method, 285getMaxHealth() method, 339getMaxStackSize() method, 286getName() method, 225getOrDefault() method, 185getPlayer() method, 326getPluginManager()

    method, 325getProperty() method, 236getReason() method, 363getRelative() method, 327getSize() method, 285getTarget() method, 362

  • How can we make this index more useful? Email us at [email protected]

    JARS (JAVA ARCHIVE FILES) 379

    getTo() method, 327getType() method, 250, 272getURI() method, 214getValue() method, 273getVirusCount() method, 160getWorld() method, 29, 244GitHub mod source code, 368godfather, 304graphical user interfaces, 324greater-than conditional, 92-93greater than operator, 92greeting variable, 44ground under players, changing.

    See StoneWalker modgrouping statements. See blocks

    Hhandling events. See eventshash maps, 184

    capacity, 184creating, 184FontMapper application,

    186-187keys/values presence,

    determining, 186load factors, 184looping through, 186mobs, 270-273objects, 185phonebook, 185size, 186

    health bars, 339-340healthcheck on/healthcheck off

    commands, 338HealthChecker mod, 336

    Bukkit class library, adding, 336

    current/maximum health, determining, 339

    deploying, 345display time, 345health bars

    colors, selecting, 340-341creating, 339-341current health points,

    calculating, 340displaying, 340scale, 340

    mobstaking damage, 338targeting players for

    attack, 339plug-in configuration file, 337

    project, creating, 336source code, 342-345turning on/off, 338

    helper classes, 157hexadecimal variables, 68HighSpeedModem class, 135holes, digging. See diggingHomePage application, 201-202hyphen (-), subtraction

    operator, 72

    IID3Reader application, 227-229IDE (integrated development

    environment), 15. See also NetBeans

    identifier variable, 148if statements, 92

    blocks, 94-96equal/not equal

    comparisons, 93less/greater-than

    comparisons, 92-93if-else statements, 96-97ignoring exceptions, 199-200implements keyword

    class statement, 324Runnable interface, 207

    importing classes, 260-261incrementing variables, 72-74increment operator (++), 72indexOf() method, 86-87, 180IndexOutOfBoundsException

    error, 200inequality operator (!=), 94infinite loops, 112inheritance, 135, 163-165

    constructors, 154hierarchy, 135JApplet class, 164-165

    initializing counter variables, 108inner classes, 311input/output. See I/Oinstalling NetBeans, 16instance variables, 134int statement, 65integers

    arraysdeclaring, 120Wheel of Fortune applica-

    tion, 129binary values, 68

    byte, 67declaring, 65floating-point, 58hexadecimal values, 68identifier variable, 148long, 67random, creating, 58short, 67underscores, 67

    integrated development environments (IDEs), 15. See also NetBeans

    interfaces, 136ActionListener, 212Listener, 324Runnable, 206-207

    inventoriesloading, 285looping through, 286materials. See materialsslots, determining, 285

    I/O (input/output), 223console input, 230files. See filesstreams

    buffered input, 229-231

    bytes, 224character, 224closing, 224, 233defined, 224reading data from,

    226-229types, 224writing data to, 232-235

    isAdult() method, 274isStoneWalking variable,

    323, 327item stacks, 285-286ItemSpawnEvent class, 352ItemSpawnEvent object, 352ItemStack class, 281iteration. See loopsiterators, 109

    JJApplet class

    inheritance, 164-165methods, 165

    JARs (Java archive files), 2ChickenStorm, 253PetWolf, finding, 33ZombieChicken, 264

  • 380 JAVA

    Javaarchive files. See JARs Bukkit class library

    documentation, 290Class Library, 56

    classes, 57documentation, 57, 61packages, 57

    Development Kit (JDK), 8Material class

    documentation, 290programs

    {} (curly brackets), 43adding to open

    projects, 40blank spaces/whitespace,

    49-50blocks, 43category, choosing, 41class statement, 42comments, 43compiling, 46defined, 38errors, 46-48main statement, 42running, 48saving, 45source code, entering, 41Splash, 38variables, 44

    Runtime Environment (JRE), 8java.io package, 58, 223java.time package, 58java.util package, 58, 235JDK (Java Development Kit), 8JohnnyApplechicken mod

    Bukkit class library, adding, 350

    cancelling chickens normal egg laying behavior, 352

    deploying, 357event handler,

    registering, 352player location, holding, 351plug-in configuration file, 350project, creating, 350source code, 354-357spawning chickens, 351tree laying capabilities,

    turning on/off, 351tree sapling supported

    blocks, 353JRE (Java Runtime

    Environment), 8

    Kkeys (hash maps), 186keywords

    implementsclass statement, 324Runnable interface, 207

    this, 325

    Llength() method, 85, 225length variable, 122-124less than operator (

  • How can we make this index more useful? Email us at [email protected]

    METHODS 381

    plugin.yml, 247-248BestFriendOfZeus

    mod, 361BigDig mod, 294HealthChecker mod, 337JohnnyApplechicken

    mod, 350MobCensus mod, 268StoneWalker mod, 322Transmuter mod, 283TreeChopper mod, 309ZombieChicken

    mod, 259Point3D class, 172-173PointTester application,

    174-175Root application source code,

    52-53SpaceRemover

    application, 123Spartacus class, 20-21Splash program, 41, 45StoneWalker.java, 328-331StringLister application,

    170-171Transmuter.java, 287-289TreeChopper.java, 314-317Variable application, 66Virus application, 159VirusLab application, 160-161Wheel of Fortune

    application, 127ZombieChicken.java, 261-264

    literals, 70load factors (hash maps), 184loading properties, 236Loc class, 311locations, 29, 132

    block materials, determining, 250

    constructor, 249getBlock() method, 250mobs

    block materials, determining, 250

    distances, calculating, 273random, 250retrieving, 273specific, 249-250

    playersdistances, calculating, 273holding, 351listening, 326-327

    searched, storing, 313spot variable, 351

    LOG variable, 244

    Logger class, 244logging server messages, 244long variables, 67loops

    array lists, 170Benchmark application,

    116-117blocks around players,

    examining, 296defined, 107do-while, 112-113exiting, 113for, 108-109

    array lists, 170complex, 115counter variables, 108empty sections, 115Nines application, 109-110spawning chickens, 351syntax, 108-109

    hash maps, 186infinite loops, 112mob census, 272names, 114-115nested, 114, 130player inventories, 286TreeChopper mod, 312while, 111

    lowercase. See case

    Mmain statement, 42makeBarGraph() method, 340MalformedURLException

    errors, 199maps (hash), 184

    capacity, 184creating, 184FontMapper application,

    186-187keys/values presence,

    determining, 186load factors, 184looping through, 186phonebook, 185retrieving objects, 185size, 186storing objects, 185

    Material class, 281, 284, 290materials

    blockschanging, 297determining, 250, 310tree saplings, planting, 353

    names, 284transmuting. See

    Transmuter modturning to stone

    eligibility, 327Math class

    documentation, 60floor() method, 58random() method, 58, 249sqrt() method, 53

    memorycontrolling, 162server lags, 310

    messagescolors, selecting, 340-341digging holes

    completion, 298TreeChopper mod, 314

    methodsaccessor, 153actionPerformed(), 216add(), 165, 169, 178addPotionEffect(), 264alert(), 153arguments, 153browse(), 216checkAuthor(), 158chopAdjacentTrees(), 312-313classes, declaring, 155close(), 224, 233constructors, 154contains(), 169containsKey(), 186containsValue(), 186createNewFile(), 225currentThread(), 215damage(), 347declaring, 151defined, 29, 85, 147, 151delete(), 225displaySpeed(), 134entrySet(), 186, 272equals(), 84, 165equalsIgnoreCase(), 243events

    handling, 326learning, 346

    executeCommand(), 243, 284-285

    exists(), 225floor(), 58get()

    array lists, 169hash maps, 185

    getAmount(), 286getBlock(), 250, 327

  • 382 METHODS

    getBytes(), 233getEntity(), 362, 338getFrom(), 327getHealth(), 339getInventory(), 285getItem(), 286getKey(), 272getLivingEntities(), 269getLocation(), 29, 244getMaterial(), 285getMaxHealth(), 339getMaxStackSize(), 286getName(), 225getOrDefault(), 185getPlayer(), 326getPlugin Manager(), 325getProperty(), 236getReason(), 363getRelative(), 327getSeconds(), 153getSize(), 285getTarget(), 362getTo(), 327getType(), 250, 272getURI(), 214getValue(), 273getVirusCount(), 160getWorld(), 29, 244indexOf(), 86-87, 180isAdult(), 274length(), 85, 225list(), 236listFiles(), 226makeBarGraph(), 340mod on status, checking, 327okToTransform(), 328onCommand(), 269

    arguments, 243StoneWalker mod, 324

    onEnable(), 362onEntityDamage(), 338onEntityTarget(), 339, 362onItemSpawn(), 352onPlayerMove(), 326overriding, 165-166, 324paint(), 166parseDouble(), 295parseInt(), 139, 155playSound(), 297println(), 77, 80-81, 151public, 152put(), 185random(), 58, 249read(), 226readLine(), 232recursion, 313registerEvents(), 325

    renameTo(), 225return values, 152run(), 207, 215-216sendMessage(), 271setAmount(), 286setBaby(), 263setBackground(), 165setCustomName(), 340setIdentifier(), 153setLayout(), 165setPassenger, 263setProperty(), 236setType(), 286setYield(), 346shoot(), 183showHealth(), 339showVirusCount(), 155signatures, 153size()

    array lists, 179hash maps, 186

    skip(), 227sleep(), 206sort(), 125spawn(), 29, 250sqrt(), 53start(), 214stop(), 211store(), 236strikeLightning(), 363substring(), 229toCharArray(), 122toLowerCase(), 85toUpperCase(), 85variable scope, 155-157write(), 232

    MinecraftEULA website, 4Mods Programming Absolute

    Beginners Guide website, 371

    projectscreating, 39opening, 40

    servers, 2Bukkit API and server

    downloads, 2Bukkit server JAR file cant

    be found error, 5connections, 9-12EULA check, 4Java virtual machine cant

    be found error, 7-9messages, logging, 244player profiles, changing, 12running first time, 4starting, 3

    website, 9

    minus sign (-), 72MobCensus mod, 268

    Bukkit class library, adding, 268

    commands, executing, 269current mobs, listing, 269deploying, 278player messages, sending, 271plug-in configuration file,

    268-269project, creating, 268source code, 274-277type counts, storing, 270-273villagers, 273-274, 279

    mobsadult/child forms, 263census, 268

    Bukkit class library, adding, 268

    commands, executing, 269current mobs, listing, 269deploying, 278player messages,

    sending, 271plug-in configuration file,

    268-269project, creating, 268source code, 274-277type counts, storing,

    270-273current health, calculating,

    339-340defined, 26found somebody to attack,

    retrieving, 362hash map, 270-273health state during battle,

    displaying. See HealthChecker mod

    lightning bolts, throwing at, 363

    locationsblock materials,

    determining, 250random, 250retrieving, 273specific, 249-250

    numbers, 248overpopulating, 249passengers, adding, 263player distance from,

    calculating, 273potions, adding, 263-264taking damage, 338targeting players for

    attack, 339targets, 362-363

  • How can we make this index more useful? Email us at [email protected]

    OPERATORS 383

    types, 270wolf, creating, 29

    classes, 31deploying, 34full text, 29-32JAR file, finding, 33troubleshooting, 34

    Modem class, 134, 142modems, 133

    CableModem class, 143DslModem class, 143Modem class, 142ModemTester class, 144

    ModemTester class, 144mods. See also specific names of

    modsas event listeners, registering,

    324-325, 362defined, 26finding, 368framework, 242-245

    CommandSender object verification, 243

    equalsIgnoreCase() method, 243

    executeCommand() method, 243

    onCommand() method, 243player locations,

    retrieving, 244Player object,

    creating, 244server messages,

    logging, 244World object access, 244

    on status, checking, 327player information, 29program, creating, 27-28projects, 26-27source code, displaying on

    GitHub, 368storing, 26turning on/off, 323

    modulus operator (%), 72Monitor objects, 133mouse clicks, handling, 216MP3 files, reading, 227-229multidimensional arrays,

    124-125multiplication operator (*), 72multithreading, 206

    Nnames

    event handling methods, 326files, 225loops, 114-115materials, 284packages, 58properties, 235, 247variables, 69-70worlds, 303

    NameSorter application, 125-126nesting

    classes, 157loops, 114, 130

    NetBeansautomatic class importing,

    260-261classes

    compiling, 20creating, 18-21running, 21

    errors, fixing, 22-23, 259installing, 16overview, 15projects, creating, 17-18source editor, 46user interface, 16website, 23

    NewRoot application, 140-141New Empty Java File dialog, 41New File Wizard, 40New Project dialog, 39New Project Wizard, 17NewCalculator application,

    193-194newline characters, 82new statement, 120, 154Nines application, 109-110NullPointerException

    error, 200NUM_CHICKENS variable, 248NumberDivider application,

    195-196NumberFormatException errors,

    194, 197numbers

    floating-point, 65integers, declaring, 65prime sequence, displaying,

    208-211

    Oobject-oriented programming.

    See OOPobjects

    advantages, 133attributes, 132, 147behavior, 132casting, 138classes, 132converting to variables, 139creating, 133-135, 142-144

    CableModem class, 143DslModem class, 143Modem class, 142ModemTester class, 144

    debugging, 133inheritance, 163-165

    hierarchy, 135JApplet class, 165

    instance variables, 134referencing, 158Server, creating, 325sharing, 168storing, 168-170thisThread, 215unboxing, 141variables, 148-149

    okToTransform() method, 328onCommand() method, 269

    arguments, 243StoneWalker mod, 324

    onEnable() method, 362onEntityDamage() method, 338onEntityTarget() method,

    339, 362onItemSpawn() method, 352onPlayerMove() method, 326OOP (object-oriented

    programming), 131-132advantages, 133debugging, 133encapsulation, 153inheritance, 135, 163-165

    hierarchy, 135JApplet class, 165

    objects. See objectsoperators

    +=, 84addition (+), 72concatenation (+), 82-83decrement (--), 72division (/), 72equality (==), 93greater than (), 92

  • 384 OPERATORS

    increment (++), 72inequality (!=), 94less than (

  • How can we make this index more useful? Email us at [email protected]

    SPOT VARIABLE 385

    properties, 235Configurator application,

    237-238converting to numerical

    values, 236displaying all, 236loading, 236names, 235, 247retrieving, 236storing, 236

    Properties class, 235protected variables, 149public methods, 152public statements, 134public variables, 149put() method, 185Pythagorean theorem, 273

    Qquestion mark (?), 99-100quotation marks

    double (), 66, 81escape codes, 82single (), 66

    Rradius, calculating, 295random() method, 58, 249random numbers, 58read() method, 226reading

    buffered input streams, 230files, 226

    ID3Reader application, 227-229

    multiple bytes, 227single bytes, 226skipping bytes, 227

    readLine() method, 232recursion, 313redwoods, 310referencing objects, 158registerEvents() method, 325registering mods as event

    listeners, 324-325, 362removing objects from arrays,

    170, 179renameTo() method, 225renaming files, 225restricting access. See access

    control

    return values (methods), 152revolving links, displaying,

    217-219Rock Proper, 229Root application, 52-53Rosenfeld, Daniel, 229run() method, 207, 215-216Runnable interface, 206-207running

    applications, 21Java programs, 48threads, 215-216

    RuntimeException class, 200

    Ssaving

    Java programs, 45properties, 236worlds, 302-304

    scope (variables), 155-157Seed numbers, 303semicolons (;), 44, 115sendMessage() method, 271servers

    lag, 310messages, 314objects, creating, 325

    setAmount() method, 286setBaby() method, 263setBackground() method, 165setCustomName() method, 340setIdentifier() method, 153setLayout() method, 165setPassenger() method, 263setProperty() method, 236setType() method, 286setYield() method, 346sharing objects, 168shoot() method, 183shooting targets, creating,

    181-183short variables, 67showHealth() method, 339showVirusCount() method, 155signatures (methods), 153single quotation marks (),

    66, 82size

    array lists, 179hash maps, 186holes, determining, 295

    size() methodarray lists, 179hash maps, 186

    skip() method, 227slashes (//), 43sleep() method, 206slowing down applications, 206sort() method, 125sorting arrays, 125-126sounds, playing, 297source code editors, 38source editor (NetBeans), 46sources (casting), 137SpaceRemover application,

    123-124spacing (Java programs), 49-50Spartacus application, 20-23

    errors, fixing, 22-23running, 21source code, 20-21

    spawn() method, 29, 250spawn points, 319spawning

    chickens, 351mobs

    block materials, determining, 250

    numbers, 248random locations, 250specific locations, 249-250

    special characters, 81-82splash messages website, 49Splash program

    adding to open projects, 40blank spaces/whitespace,

    49-50blocks, 43{} (curly brackets), 43category, choosing, 41class statement, 42comments, 43compiling, 46errors

    cannot find symbol, 47displaying, 46line numbers, 48spelling/punctuation, 48

    line-by-line breakdown, 45main statement, 42running, 48saving, 45source code, 41variables, 44

    spot variable, 351

  • 386 SQRT() METHOD

    sqrt() method, 53square brackets ([]), 284start() method, 214starting

    Minecraft servers, 3threads, 207, 210-214values, 70-71

    statementsblocks, 64, 94-96break, 98, 113case, 97class, 42, 134, 324conditionals. See conditionalscontinue, 113default, 98defined, 64expressions, 75

    advantages