Barry Burd

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

Articles From Barry Burd

page 1
page 2
page 3
page 4
page 5
48 results
48 results
Coding All-in-One For Dummies Cheat Sheet

Cheat Sheet / Updated 06-30-2022

Coding is equal parts vocabulary, logic, and syntax. Coding may at first seem intimidating, but with practice, though, it's easy to get comfortable with its terminology, concepts, and structure. Understanding coding is not unlike learning a new language: Use it often enough and you'll find yourself able to speak, think, and write in code. Still, it's natural for beginners to have questions. There are many coding resources available to you, both on- and off-line. Ask around and you'll find you're not alone — many other people are learning. After all, coding is a never-ending education. Master one facet or another and a new one opens in front of you.

View Cheat Sheet
Java For Dummies Cheat Sheet

Cheat Sheet / Updated 02-25-2022

When doing anything with Java, you need to know your Java words — those programming words, phrases, and nonsense terms that have specific meaning in the Java language, and get it to do its thing. This Cheat Sheet tells you all about Java's categories of words.

View Cheat Sheet
Flutter For Dummies Cheat Sheet

Cheat Sheet / Updated 02-14-2022

Flutter's online documentation is a great source of information, but sometimes you'd rather glance quickly at an example. This cheat sheet has some sample code. Just grab it and go!

View Cheat Sheet
Firing up IntelliJ IDEA

Article / Updated 01-24-2022

Imagine that you’re expecting a delivery from a local confectioner. In the late afternoon, the mail carrier delivers a box containing your favorite chocolate candy. Naturally, you want to open the box as soon as it arrives. The same is true about this book’s software. Here’s how you open your newly downloaded IntelliJ IDEA box: Launch the IntelliJ IDEA application. When you do, you see a flashy banner display. After a few seconds, the banner disappears and you see the Welcome to IntelliJ IDEA dialog box. The box is shown in Figure 2-1. You can change the IntelliJ color theme by selecting Customize in the Welcome dialog box’s side panel. In the Welcome dialog box, choose New Project. A Java application may consist of several files, including code files, image files, data files, installation instructions, and other stuff. With IntelliJ IDEA, you manage an application’s files by combining them into a single project. In this book, a typical project contains only one file. Why bother “collecting” one file into a bigger thing called a “project”? The answer is, IntelliJ IDEA wants each application to be part of a project, just in case the application grows to include dozens or even hundreds of files. When you select New Project, a dialog box appears. To no one’s surprise, the box’s title is New Project. (See Figure 2-2.) Make sure that the topmost entry (namely, Java) is selected in the dialog box’s side panel. (Refer to Figure 2-2.) At the top of the dialog box’s main body, look for the drop-down list labeled Project SDK. (Refer again to Figure 2-2.) The letters SDK stand for software development kit. During its long history, Java has come in many different shapes and sizes. Even now, the kind of Java you run depends on the kind of Java you need. This drop-down box asks you to select the kind of Java you’ll be using in your new project. For more than you’d like to know about Java’s many incarnations, see the later section “The Java smorgasbord.” What you do next depends on what you see in that drop-down list. If you see in the drop-down list, jump temporarily to the later section “Installing Java.” Likewise, if you see Version 16 or any version lower than 16 (including versions like 1.8.0_241) in the drop-down list, jump temporarily to the later section “Installing Java.” If you see Version 17 or any version number higher than 17, leave the drop-down list as it is and click Next. After clicking Next, you see a second New Project dialog box. You can proceed to the next step in this list of instructions. The second New Project dialog box displays the Create Project from Template check box. Put a check mark in the Create Project from Template check box. (See Figure 2-3.) In the same New Project dialog box, make sure that the Command Line App item is selected. (Refer again to Figure 2-3.) At the bottom of this New Project dialog box, click Next. When you click Next, a third (and, thankfully, final) New Project dialog box asks for a project name, a project location, and a base package (See Figure 2-4.) For the project name, almost any sequence of characters will do. In Figure 2-4, I use the name 02-01. After all, this is Chapter 2, and this is the first (and only) project in Chapter 2. For the project location, I recommend keeping the default. Delete any text in the Base Package field. (Refer to 2-4.) My Java colleagues will rip me to pieces for telling you to leave the Base Package field empty. A package is a group of one or more Java code files, and experienced Java professionals never write code without naming a package. The trouble is, having a named base package would make it slightly more difficult for you to run this book’s sample programs. The quickest (and dirtiest) solution is to have you clear out the Base Package field. Don’t tell anyone. It’s our little secret. In this final New Project dialog box, click Finish. At last! IntelliJ’s main window appears on your computer screen. Figure 2-5 contains a screen shot of the main window. In the figure, I’ve labeled a few of the main window’s parts. It may take a while for IntelliJ to finish creating a new project. You may see only a big gray area in most of the main window. You may see some messages about indexing on the status bar. If so, be patient. Wait for the text on the status bar to stop changing. Figure 2-6 shows what you see when the status bar in Figure 2-5 stops changing. With no turmoil on the status bar, you may still not see the Editor or the Project tool window. If you don’t see the Project tool window, you can coax it out of hiding: Just click the Project tool button along the window’s leftmost edge. If you don’t see the Editor, expand the Project tool window’s tree and double-click the tree’s Main branch. (Refer to Figure 2-5.) Enough preliminaries. It’s time to run some Java code. Click the Run button. When you do, you should see some new messages on the IntelliJ status bar. After a number of seconds, you see a new tool window — the IntelliJ Run tool window — along the bottom of the screen. (See Figure 2-7.) Along with some technical gobbledygook, the Run tool window displays the words Process finished with exit code 0. That’s it! You’re done setting up the software. For answers to questions about any of these steps, see the later section “If You Need More Details . . . .” Installing Java What? You say you were following the previous section’s steps and then Step 5 in that section made you take a detour? Well, you’ve come to the right place! When you reached Step 5, you were staring at the New Project dialog box. Maybe the text appeared in the dialog box’s Project SDK drop-down list. (Refer to Figure 2-2.) Or maybe the drop-down list displayed a version number lower than 17. In either case, here’s what you do next: In the Project SDK drop-down list, select Download JDK. (See Figure 2-8.) When you select Download JDK, IntelliJ displays a new Download JDK dialog box. (See Figure 2-9.) In the Download JDK dialog box’s Version list, select the highest number available. For the Vendor drop-down list, I recommend the Oracle OpenJDK option. I don’t have a particularly good reason for recommending this option. Oracle owns the rights to Java, so using Oracle’s product means getting Java “from the horse’s mouth.” And the prefix Open in OpenJDK means that this version of Java is free to use for noncommercial purposes. No matter which vendor option you pick, you’ll be okay. This book’s examples run on any newer version of Java. The third item in the Download JDK dialog box is a Location field. In the Location field, your safest move is to accept the default. In other words, leave that field alone. When you’re finished making selections, click the Download button. As if by magic, IntelliJ downloads Java and installs it on your computer. In the New Project dialog box, click Next. As a result, another dialog box with the same title (New Project) appears. With this second New Project dialog box staring you in the face, you can return to Step 6 in the previous section. It was fun guiding you through this section’s steps. Please say hello to the “Firing up IntelliJ IDEA” section for me!

View Article
Java Programming: Telling the Computer to Do Something

Article / Updated 01-13-2022

In Listing 1, below, you get a blast of Java code. Like all novice programmers, you're expected to gawk humbly at the code. But don't be intimidated. When you get the hang of it, programming is pretty easy. Yes, it's fun, too. Listing 1: A Simple Java Program /* * A program to list the good things in life * Author: Barry Burd, [email protected] * February 10, 2021 */ public class ThingsILike { public static void main (String[] args) { System.out.println("Chocolate, royalties, sleep"); } } Buried deep in the heart of Listing 1 is the single line that actually issues a direct instruction to the computer. The line System.out.println("Chocolate, royalties, sleep"); tells the computer to display the words Chocolate, royalties, sleep in the command prompt window. This line can be described in at least two different ways: It's a statement: In Java, a direct instruction that tells the computer to do something is called a statement. The statement in Listing 1 tells the computer to display some text. The statements in other programs may tell the computer to put 7 in certain memory location, or make a window appear on the screen. The statements in computer programs do all kinds of things. It's a method call: A method call is a separate piece of code (in a different part of the Java program) that tells the computer to call the method into action.The statement <tt>FixTheAlternator(junkyOldFord);</tt> is an example of a method call, and so is <tt>System.out.println("Chocolate, royalties, sleep");</tt> Java has many different kinds of statements. A method call is just one kind. Ending a statement with a semicolon In Java, each statement ends with a semicolon. The code in Listing 1 has only one statement in it, so only one line in Listing 1 ends with a semicolon. Take any other line in Listing 1, like the method header, for instance. The method header (the line with the word main in it) doesn't directly tell the computer to do anything. Instead, the method header describes some action for future reference. The header announces "Just in case someone ever calls the main method, the next few lines of code tell you what to do in response to that call." Every complete Java statement ends with a semicolon. A method call is a statement, so it ends with a semicolon, but neither a method header nor a method declaration is a statement. The method named System.out.println The statement in the middle of Listing 1 calls a method named System.out.println. This method is defined in the Java API. Whenever you call the System.out.println method, the computer displays text on its screen. Think about the name Pauline Ott, for example. Believe it or not, I know two people named Pauline Ott. One of them is a nun; the other is physicist. Of course, there are plenty of Paulines in the English-speaking world, just as there are several things named println in the Java API. So to distinguish the physicist Pauline Ott from the film critic Pauline Kael, write the full name "Pauline Ott." And, to distinguish the nun from the physicist, write "Sister Pauline Ott." In the same way, write either System.out.println or DriverManager.println. The first writes text on the computer's screen. The second writes to a database log file. Just as Pauline and Ott are names in their own right, so System, out, and println are names in the Java API. But to use println, you must write the method's full name. You never write println alone. It's always System.out.println or some other combination of API names. The Java programming language is case-sensitive. If you change a lowercase letter to an uppercase letter (or vice versa), you change a word's meaning. You can't replace System.out.println with system.out.Println. If you do, your program won't work. The Java class You may have heard the term object-oriented programming (also known as OOP). OOP is a way of thinking about computer programming problems — a way that's supported by several different programming languages. OOP started in the 1960s with a language called Simula. It was reinforced in the 1970s with another language named Smalltalk. In the 1980s, OOP took off big time with the language C++. Some people want to change the acronym, and call it COP, class-oriented programming. That's because object-oriented programming begins with something called a class. In Java, everything starts with classes, everything is enclosed in classes, and everything is based on classes. In Java, your main method has to be inside a class. The code in Listing 1 starts with the words class ThingsILike. Take another look at Listing 1, and notice what happens after the line class ThingsILike. The rest of the code is enclosed in curly braces. These braces mark all the stuff inside the class. Without these braces, you'd know where the declaration of the ThingsILike class starts, but you wouldn't know where the declaration ends. It's as if the stuff inside the ThingsILike class is in a box. To box off a chunk of code, you do two things: You use curly braces: These curly braces tell the compiler where a chunk of code begins and ends. You indent code: Indentation tells your human eye (and the eyes of other programmers) where a chunk of code begins and ends. Don't forget. You have to do both.

View Article
Getting Started with Java Programming

Article / Updated 01-13-2022

The late 1980s saw several advances in software development, and by the early 1990s, many large programming projects were being written from prefab components. Java came along in 1995, so it was natural for the language's founders to create a library of reusable code. The library included about 250 programs, including code for dealing with disk files, code for creating windows, and code for passing information over the Internet. Since 1995, this library has grown to include more than 4,000 programs. This library is called the Application Programming Interface (API). Every Java program, even the simplest one, calls on code in the Java API. This Java API is both useful and formidable. It's useful because of all the things you can do with the API's programs. It's formidable because the API is so extensive. No one memorizes all the features made available by the Java API. Programmers remember the features that they use often, and look up the features that they need in a pinch. So many ways to write computer programs To write Java programs, you need four tools: A Java compiler A Java Virtual Machine. The Java API. The Java API documentation. The Java smorgasbord This section explains some of the terminology you might see as you travel through the Java ecosystem. Medium Java, little Java, and gigantic Java At some point, you may see mention of Java SE, Java ME, or Java EE. Here’s the lowdown on these three kinds of “Java E”: Java Standard Edition (Java SE): This is the only edition you should think about (for now, anyway). Java SE includes all the code you need in order to create general-purpose applications on a typical computer. Nowadays, when you hear the word Java, it almost always refers to Java SE. Java Micro Edition (Java ME): The Micro Edition contains code for programming special-purpose devices such as television sets, printers, and other gadgets. Java Enterprise Edition (Java EE): In 1999, the stewards of Java released an edition that was tailored for the needs of big companies. The starring role in this edition was a framework called Enterprise JavaBeans — a way of managing data storage across connected computers. In 2017, Oracle walked away from Java EE, handing it over to the Eclipse Foundation, which renamed it Jakarta EE. The rest of this book deals exclusively with Java Standard Edition. How do you type this stuff? A computer program is a big piece of text. So to write a computer program, you need a text editor — a tool for creating text documents. A text editor is a lot like Microsoft Word, or like any other word processing program. The big difference is that the documents that you create with a text editor have no formatting whatsoever. They have no bold, no italic, no distinctions among fonts. They have nothing except plain old letters, numbers, and other familiar keyboard characters. That's good, because computer programs aren't supposed to have any formatting. A document with no formatting is called a plain text document. Documents without formatting are fairly simple things, so a typical text editor is easier to use than a word processing program. (Text editors are a lot cheaper than word processing programs, and they're lightning fast. Even better, text editors take very little space on your hard drive.) You can use a word processor, like Microsoft Word, to create program files. But, by default, word processors insert formatting into your document. This formatting makes it impossible for a Java compiler to do its job. Using word processors to write Java programs isn't recommended. But, if you must use a word processor, be sure to save your source files with the .java extension. (Call a file SomeName.java.) Remember, also, to use the Save As command to save with the plain text file type. Using a customized editor Even if you don't use an integrated development environment, you can use other tools to make your programming life easy. Think, for a moment, about an ordinary text editor — an editor like Windows Notepad. With Notepad you can Create a document that has no formatting Find and replace characters, words, and other strings Copy, cut, and paste Print Not much else Notepad is fine for writing computer programs. But if you plan to do a lot of programming, you may want to try a customized editor. These editors do more than Windows Notepad. They have Syntax highlighting Shortcuts for compiling and running programs Explorer-like views of your works in progress Code completion Other cool stuff When it comes to choosing a custom editor, one favorite is IntelliJ IDEA. IntelliJ Idea comes in two different editions: Ultimate Edition or Community Edition. The Community Edition is free. To download the IntelliJ IDEA Community Edition, visit www.jetbrains.com/idea/download.

View Article
Tackling Error Messages in Java Programming

Article / Updated 01-13-2022

Sometimes, error messages can strike fear into the heart of even the bravest programmer. Fortunately some helpful, calming advice is here — advice to help you solve the problem when you see one of these messages. NoClassDefFoundError You get this error when you're trying to run your code. So first ask yourself, did you attempt to compile the code? If so, did you see any error messages when you compiled? If you saw error messages, look for things you can fix in your .java file. Try to fix these things, and then compile the .java file again. If you normally keep code in the JavaPrograms directory, make sure that you're still working in this JavaPrograms directory. (In Windows, make sure that the command prompt says JavaPrograms.) Make sure you have an appropriately named .class file in your working directory. For instance, if you're trying to run a program named MyGreatProg, look for a file named MyGreatProg.class in your working directory. Check your classpath to make sure that it contains the .class file that you need. For example, if all your Java code is in your working directory, make sure that the classpath includes a dot. NoSuchMethodError When you encounter this error message, check for the misspelling or inconsistent capitalization of a method name. Check the capitalization of main (not Main). When you issue the java command (or do whatever you normally do to run a program in your environment), does the class that you're trying to run contain its own main method? If not, then find the class with the main method and run that class instead. Cannot Resolve Symbol If you get an error message that includes cannot resolve symbol, check the spelling and capitalization of all identifiers and keywords. Then check again. If the unresolved symbol is a variable, make sure that this variable's declaration is in the right place. For instance, if the variable is declared in a for loop's initialization, are you trying to use that variable outside the for loop? If the variable is declared inside a block (a pair of curly braces), are you trying to use that variable outside of the block? Finally, look for errors in the variable's declaration. If the compiler finds errors in a variable's declaration, then the compiler can't resolve that variable name in the remainder of the code. Expected ';' (Or Expected Something Else) When you see an error message that says ';' expected, go through your code and make sure that each statement and each declaration ends with a semicolon. If so, then maybe the compiler's guess about a missing semicolon is incorrect. Fixing another (seemingly unrelated) error and recompiling your code may get rid of a bogus ';' expected message. For a missing parenthesis, check the conditions of if statements and loops. Make sure each condition is enclosed in parentheses. Also, make sure that a parameter list (enclosed in parentheses) follows the name of each method. For an expected message, check your assignment statements. Make sure that each assignment statement is inside a method. (Remember, a declaration with an initialization can be outside of a method, but each plain old assignment statement must be inside a method.) For the 'class' or 'interface' expected message, make sure you've spelled the word class correctly. If your code has an import declaration, check the spelling and capitalization of the word import. Missing Method Body or Declare Abstract You get a missing method body or declare abstract message when the compiler sees a method header, but the compiler can't find the method's body. Look at the end of the method's header. If you ended the header with a semicolon, then try removing the semicolon. If the header doesn't end with a semicolon, then check the code immediately following the header. The code immediately following the header should start with an open curly brace (the beginning of a method body). If some code comes between the header and the body's open curly brace, consider moving that code somewhere else. An 'else' without an 'if' Compare the number of if clauses with the number of else clauses. An if clause doesn't need to have an else clause, but each else clause must belong to an if clause. Remember, you enclose an if condition in parentheses, but you don't put a semicolon after the condition. Did you mistakenly end an if condition with a semicolon? Look at all the lines between an if and its else. When you find more than one statement between an if and its else, look for curly braces. If the statements between the if and its else aren't surrounded by curly braces, you may have found the culprit. Non-static Variable Cannot Be Referenced from a Static Context Lots of things can give you a non-static variable cannot be referenced from a static context error message. But for beginning programmers, the most common cause is having a variable that's declared outside of the main method. It's no sin to declare such a variable, but because the main method is always static, you need some special help to make the main method refer to a variable that's declared outside the main method. The quickest solution is to put the word static in front of the variable's declaration. But first, ask yourself why this variable's declaration isn't inside the main method. If there's no good reason, then move the variable's declaration so that it's inside the main method. FileNotFoundException (The System Cannot Find the File Specified) or EOFException If you encounter a FileNotFoundException message, check that the file named in your code actually exists. (Look for the file using your system's explorer or using the command prompt window.) Double-check the spelling in your code against the name of the file on your hard drive. If you've found a correctly named file on your hard drive, make sure that the file is in the correct directory. (For a program running in your working directory, a typical data file is in the working directory also.) If you're a Windows user, make sure that the system didn't add an extra .txt extension when you created the file. (Use the command prompt window to check the file's name. Windows Explorer can hide the .txt extension, and that always leads to confusion.) For an EOFException, you're probably trying to read more data than you have in the file. Very often, a small logic error makes your program do this. So do a careful review of all the steps in your program's execution. Look for subtle things, like improperly primed loops or the reading of array values past the array's largest index. Look for conditions that use <= when they should use <. Conditions like these can often be troublesome.

View Article
How to Generate Words Randomly in Java

Article / Updated 01-13-2022

Most Java programs don’t work correctly the first time you run them, and some programs don’t work without extensive trial and error on your part. This code is a case in point. To write this code, you need a way to generate three-letter words randomly. This code would give you the desired result: anAccount.lastName = " + (char) (myRandom.nextInt(26) + 'A') + (char) (myRandom.nextInt(26) + 'a') + (char) (myRandom.nextInt(26) + 'a'); Here’s how the code works: Each call to the Random.nextInt(26) generates a number from 0 to 25. Adding 'A' gives you a number from 65 to 90. To store a letter 'A', the computer puts the number 65 in its memory. That’s why adding 'A' to 0 gives you 65 and why adding 'A' to 25 gives you 90. Applying (char) to a number turns the number into a char value. To store the letters 'A' through 'Z', the computer puts the numbers 65 through 90 in its memory. So applying (char) to a number from 65 to 90 turns the number into an uppercase letter. Pause for a brief summary. The expression (char) (myRandom.nextInt(26) + 'A') represents a randomly generated uppercase letter. In a similar way, (char) (myRandom.nextInt(26) + 'a') represents a randomly generated lowercase letter. Watch out! The next couple of steps can be tricky. Java doesn’t allow you to assign a char value to a string variable. The following statement would lead to a compiler error: //Bad statement: anAccount.lastName = (char) (myRandom.nextInt(26) + 'A'); In Java, you can use a plus sign to add a char value to a string. When you do, the result is a string. So "" + (char) (myRandom.nextInt(26) + 'A') is a string containing one randomly generated uppercase character. And when you add (char) (myRandom.nextInt(26) + 'a') onto the end of that string, you get another string — a string containing two randomly generated characters Finally, when you add another (char) (myRandom.nextInt(26) + 'a') onto the end of that string, you get a string containing three randomly generated characters. So you can assign that big string to anAccount.lastName. That’s how the statement works. When you write a program, you have to be very careful with numbers, char values, and strings. This isn’t the kind of programming you do every day of the week, but it is a lesson that you need to be persistent in your Java programming.

View Article
How to Write Java Code to Show an Image on the Screen

Article / Updated 01-13-2022

You will probably find times when programming with Java that you need to display a window on your computer screen. This code has very little logic of its own. Instead, this code pulls together a bunch of classes from the Java API. import javax.swing.JFrame; import javax.swing.ImageIcon; import javax.swing.JLabel; class ShowPicture { public static void main(String args[]) { var frame = new JFrame(); var icon = new ImageIcon("androidBook.jpg"); var label = new JLabel(icon); frame.add(label); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } } You can create an instance of the Purchase class with the line var purchase1 = new Purchase(); So in the code, you can do the same kind of thing. You can create instances of the JFrame, ImageIcon, and JLabel classes with the following lines: var frame = new JFrame(); var icon = new ImageIcon("androidBook.jpg"); var label = new JLabel(icon); Here’s some gossip about each of these lines: A JFrame is like a window (except that it’s called a JFrame, not a “window”). The line var frame = new JFrame(); creates a JFrame object, but this line doesn’t display the JFrame object anywhere. (The displaying comes later in the code.) An ImageIcon object is a picture. At the root of the program's project directory, there is a file named androidBook.jpg. That file contains the picture. The line var icon = new ImageIcon("androidBook.jpg"); creates an ImageIcon object — an icon containing the androidBook.jpg picture. You can use almost any .gif, .jpg, or .png file in place of the (lovely) Android book cover image. To do so, drag your own image file to Eclipse's Package Explorer. (Drag it to the root of this example's project folder.) Then, in Eclipse's editor, change the name androidBook.jpg to your own image file's name. That's it! You need a place to put the icon. You can put it on something called a JLabel. The line var label = new JLabel(icon); creates a JLabel object and puts the androidBook.jpg icon on the new label’s face. If you read the previous bullets, you may get a false impression. The wording may suggest that the use of each component (JFrame, ImageIcon, JLabel, and so on) is a logical extension of what you already know. “Where do you put an ImageIcon? Well of course, you put it on a JLabel.” When you’ve worked long and hard with Java’s Swing components, all these things become natural to you. But until then, you look everything up in Java's API documentation. You never need to memorize the names or features of Java’s API classes. Instead, you keep Java’s API documentation handy. When you need to know about a class, you look it up in the documentation. If you need a certain class often enough, you’ll remember its features. For classes that you don’t use often, you always have the docs.

View Article
How to Store Values in an Array in Java

Article / Updated 01-05-2022

After you’ve created an array in Java, you can put values into the array’s components. For example, imagine you are the owner of a motel. The guests in Room 6 are fed up with all those mint candies that you put on peoples’ beds. They check out, and Room 6 becomes vacant. You should put the value 0 into the 6 component. You can do it with this assignment statement: guestsIn[6] = 0; On one weekday, business is awful. No one’s staying at the motel. But then you get a lucky break. A big bus pulls up to the motel. The side of the bus has a sign that says “Loners’ Convention.” Out of the bus come 25 people, each walking to the motel’s small office, none paying attention to the others who were on the bus. Each person wants a private room. Only 10 of them can stay at the Java Motel, but that’s okay, because you can send the other 15 loners down the road to the old C-Side Resort and Motor Lodge. Anyway, to register ten of the loners into the Java Motel, you put one guest in each of your ten rooms. Having created an array, you can take advantage of the array’s indexing and write a for loop, like this: for (int roomNum = 0; roomNum < 10; roomNum++) { guestsIn[roomNum] = 1; } This loop takes the place of ten assignment statements because the computer executes the statement guestsIn[roomNum] = 1 ten times. The first time around, the value of roomNum is 0, so in effect, the computer executes guestsIn[<b>0</b>] = 1; In the next loop iteration, the value of roomNum is 1, so the computer executes the equivalent of the following statement: guestsIn[<b>1</b>] = 1; During the next iteration, the computer behaves as if it’s executing guestsIn[<b>2</b>] = 1; And so on. When roomNum gets to be 9, the computer executes the equivalent of the following statement: guestsIn[<b>9</b>] = 1; Notice that the loop’s counter goes from 0 to 9. Remember that the indices of an array go from 0 to one fewer than the number of components in the array. Looping with room numbers from 0 to 9 covers all the rooms in the Java Motel. When you work with an array, and you step through the array’s components using a for loop, you normally start the loop’s counter variable at 0. To form the condition that tests for another iteration, you often write an expression like roomNum < arraySize, where arraySize is the number of components in the array.

View Article
page 1
page 2
page 3
page 4
page 5