85Chapter 4: Exploring the Parts of a Program When you run the ThingsILike program, you see the words Chocolate, royalties, sleep on the screen. In Listing 4-1, the text \"Chocolate, royalties, sleep\" refers to these words, exactly as they appear on the screen (minus the quotation marks). Most of the numbers that you use in computer programs are literals. If you put the statement mySalary = 1000000.00; in a computer program, then 1000000.00 is a literal. It stands for the number 1000000.00 (one million). If you don’t enjoy counting digits, you can put the following statement in your Java 7 program: mySalary = 1_000_000.00; Starting with Java 7, numbers with underscores are permissible as literals. In versions of Java before Java 7, you cannot use numbers such as 1_000_000.00 in your code. Different countries use different number separators and different number formats. For example, in the United States, you write 1,234,567,890,55. In France, you write 1234567890,55. In India, you group digits in sets of two and three. You write 1,23,45,67,890.55. You can’t put a statement like mySalary = 1,000,000.00 in your Java program. Java’s numeric literals don’t have any commas in them. But you can write mySalary = 10_00_000.00 for easy- to-read programming in India. And for a program’s output, you can display numbers like 1234567890,55 using Java’s Locale and NumberFormat classes. (For more on Locale and NumberFormat, check out Chapter 18.) Punctuation A typical computer program has lots of punctuation. For example, consider the program in Listing 4-1: class ThingsILike { public static void main(String args[]) { System.out.println(\"Chocolate, royalties, sleep\"); } } Each bracket, each brace, each squiggle of any kind plays a role in making the program meaningful.
86 Part II: Writing Your Own Java Programs In English, you write all the way across one line and then you wrap your text to the start of the next line. In programming, you seldom work this way. Instead, the code’s punctuation guides the indenting of certain lines. The indentation shows which parts of the program are subordinate to which other parts. It’s as though, in English, you wrote Suzanne’s sentence like this: Suzanne says “eh” because , as you know , she lives in Canada. The diagrams in Figures 4-3 and 4-4 show you how parts of the ThingsILike program are contained inside other parts. Notice how a pair of curly braces acts like a box. To make the program’s structure visible at a glance, you indent all the stuff inside of each box. Figure 4-3: A pair of curly braces acts like a box. Figure 4-4: The ideas in a computer program are nested inside one another. I can’t emphasize this point enough. If you don’t indent your code or if you indent but you don’t do it carefully, then your code still compiles and runs correctly. But this successful run gives you a false sense of confidence. The minute you try to update some poorly indented code, you become hopelessly confused. So take my advice: Keep your code carefully indented at every step in the process. Make your indentation precise, whether you’re scratching out a quick test program or writing code for a billionaire customer. Eclipse can indent your code automatically for you. Select the .java file whose code you want to indent. Then, in Eclipse’s main menu, choose Source➪Format. Eclipse rearranges your lines in the editor, indenting things that should be indented and generally making your code look good.
87Chapter 4: Exploring the Parts of a Program Comments A comment is text that’s outside the normal flow. In Figure 4-2, the words “A comment:” aren’t part of the Suzanne sentence. Instead, these words are about the Suzanne sentence. The same is true of comments in computer programs. The first five lines in Listing 4-1 form one big comment. The computer doesn’t act on this comment. There are no instructions for the computer to perform inside this comment. Instead, the comment tells other programmers something about your code. Comments are for your own benefit, too. Imagine that you set aside your code for a while and work on something else. When you return later to work on the code again, the comments help you remember what you were doing. The Java programming language has three kinds of comments: ✓ Traditional comments: The comment in Listing 4-1 is a traditional comment. The comment begins with /* and ends with */. Everything between the opening /* and the closing */ is for human eyes only. Nothing between /* and */ gets translated by the compiler. The second, third, and fourth lines in Listing 4-1 have extra asterisks. I call them “extra” because these asterisks aren’t required when you create a comment. They just make the comment look pretty. I include them in Listing 4-1 because, for some reason that I don’t entirely understand, most Java programmers add these extra asterisks. ✓ End-of-line comments: Here’s some code with end-of-line comments: class ThingsILike { //Two things are missing public static void main(String args[]) { System.out.println(\"sleep\"); // Missing from here } } An end-of-line comment starts with two slashes and goes to the end of a line of type. You may hear programmers talk about commenting out certain parts of their code. When you’re writing a program and something’s not work- ing correctly, it often helps to try removing some of the code. If nothing else, you find out what happens when that suspicious code is removed. Of course, you may not like what happens when the code is removed, so you don’t want to delete the code completely. Instead, you turn your ordi- nary Java statements into comments. For example, turn System.out. println(\"Sleep\"); into /* System.out.println(\"Sleep\"); */. This keeps the Java compiler from seeing the code while you try to figure out what’s wrong with your program.
88 Part II: Writing Your Own Java Programs ✓ Javadoc comments: A special Javadoc comment is any traditional com- ment that begins with an extra asterisk. /** * Print a String and then terminate the line. */ This is a cool Java feature. The software that you can download from java.sun.com includes a little program called javadoc. The javadoc program looks for these special comments in your code. The program uses these comments to create a brand new web page — a customized documentation page for your code. To find out more about turning Javadoc comments into web pages, visit this book’s website (http:// allmycode.com/BeginProg). Understanding a Simple Java Program The following sections present, explain, analyze, dissect, and otherwise demystify the Java program in Listing 4-1. What is a method? You’re working as an auto mechanic in an upscale garage. Your boss, who’s always in a hurry and has a habit of running words together, says, “FixThe Alternator on that junkyOldFord.” Mentally, you run through a list of tasks. “Drive the car into the bay, lift the hood, get a wrench, loosen the alternator belt,” and so on. Three things are going on here: ✓ You have a name for the thing you’re supposed to do. The name is FixTheAlternator. ✓ In your mind, you have a list of tasks a ssociated with the name FixThe Alternator. The list includes “Drive the car into the bay, lift the hood, get a wrench, loosen the alternator belt,” and so on. ✓ You have a grumpy boss who’s telling you to do all this work. Your boss gets you working by saying, “FixTheAlternator.” In other words, your boss gets you working by saying the name of the thing you’re sup- posed to do. In this scenario, using the word method wouldn’t be a big stretch. You have a method for doing something with an alternator. Your boss calls that method into action, and you respond by doing all the things in the list of instructions that you’ve associated with the method.
89Chapter 4: Exploring the Parts of a Program Java methods If you believe all that stuff in the preceding section, then you’re ready to read about Java methods. In Java, a method is a list of things to do. Every method has a name, and you tell the computer to do the things in the list by using the method’s name in your program. I’ve never written a program to get a robot to fix an alternator. But, if I were to, the program might include a method named FixTheAlternator. The list of instructions in my FixTheAlternator method would look something like the text in Listing 4-2. Listing 4-2: A Method Declaration void FixTheAlternator() { DriveInto(car, bay); Lift(hood); Get(wrench); Loosen(alternatorBelt); ... } Somewhere else in my Java code (somewhere outside of Listing 4-2), I need an instruction to call my FixTheAlternator method into action. The instruc- tion to call the FixTheAlternator method into action may look like the line in Listing 4-3. Listing 4-3: Calling a Method FixTheAlternator(junkyOldFord); Don’t scrutinize Listings 4-2 and 4-3 too carefully. All the lines of code in Listings 4-2 and 4-3 are fakes! I made up this code so that it looks a lot like real Java code, but it’s not real. What’s more important, the code in Listings 4-2 and 4-3 isn’t meant to illustrate all the rules about Java. So if you have a grain of salt handy, take it with Listings 4-2 and 4-3. Almost every computer programming language has something akin to Java’s methods. If you’ve worked with other languages, you may remember things like subprograms, procedures, functions, subroutines, Sub procedures, or PERFORM statements. Whatever you call it in your favorite programming language, a method is a bunch of instructions collected together and given a new name.
90 Part II: Writing Your Own Java Programs The declaration, the header, and the call If you have a basic understanding of what a method is and how it works (see preceding section), you can dig a little deeper into some useful terminology: ✓ If I’m being lazy, I refer to the code in Listing 4-2 as a method. If I’m not being lazy, I refer to this code as a method declaration. ✓ The method declaration in Listing 4-2 has two parts. The first line (the part with the name FixTheAlternator in it, up to but not including the open curly brace) is called a method header. The rest of Listing 4-2 (the part surrounded by curly braces) is a method body. ✓ The term method declaration distinguishes the list of instructions in Listing 4-2 from the instruction in Listing 4-3, which is known as a method call. For a handy illustration of all the method terminology, see Figure 4-5. Figure 4-5: The ter- minology describing methods. A method’s header and body are like an entry in a dictionary. An entry doesn’t really use the word that it defines. Instead, an entry tells you what happens if and when you use the word.
91Chapter 4: Exploring the Parts of a Program chocolate (choc-o-late) n. 1. The most habit-forming substance on earth. 2. Something you pay for with money from royalties. 3. The most impor- tant nutritional element in a person’s diet. FixTheAlternator( ) Drive the car into the bay, lift the hood, get the wrench, loosen the alternator belt, and then eat some chocolate. In contrast, a method call is like the use of a word in a sentence. A method call sets some code in motion. “I want some chocolate, or I’ll throw a fit.” “FixTheAlternator on that junkyOldFord.” A method’s declaration tells the computer what will happen if you call the method into action. A method call (a separate piece of code) tells the com- puter to actually call the method into action. A method’s declaration and the method’s call tend to be in different parts of the Java program. The main method in a program In Listing 4-1, the bulk of the code is the declaration of a method named main. (Just look for the word main in the code’s method header.) For now, don’t worry about the other words in the method header — the words public, static, void, String, and args. I explain these words (on a need-to-know basis) in the next several chapters. Like any Java method, the main method is a recipe: How to make biscuits: Preheat the oven. Roll the dough. Bake the rolled dough. or How to follow the main instructions in the ThingsILike code: Display Chocolate, royalties, sleep on the screen. The word main plays a special role in Java. In particular, you never write code that explicitly calls a main method into action. The word main is the name of the method that is called into action automatically when the pro- gram begins running.
92 Part II: Writing Your Own Java Programs When the ThingsILike program runs, the computer automatically finds the program’s main method and executes any instructions inside the method’s body. In the ThingsILike program, the main method’s body has only one instruction. That instruction tells the computer to print Chocolate, royalties, sleep on the screen. None of the instructions in a method are executed until the method is called into action. But if you give a method the name main, that method is called into action automatically. How you finally tell the computer to do something Buried deep in the heart of Listing 4-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. (If you use Eclipse, the computer displays Chocolate, royalties, sleep in the Console view.) I can describe this line of code 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 4-1 tells the computer to display some text. The statements in other programs may tell the computer to put 7 in a 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. In the “What is a method?” section, earlier in this chapter, I describe something named a “method call.” The statement FixTheAlternator(junkyOldFord); is an example of a method call, and so is System.out.println(\"Chocolate, royalties, sleep\"); Java has many different kinds of statements. A method call is just one kind.
93Chapter 4: Exploring the Parts of a Program Ending a statement with a semicolon In Java, each statement ends with a semicolon. The code in Listing 4-1 has only one statement in it, so only one line in Listing 4-1 ends with a semicolon. Take any other line in Listing 4-1, like the method header, for example. 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 4-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 names. Believe it or not, I know two people named Pauline Ott. One of them is a nun; the other is a 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, I write the full name “Pauline Ott.” And to distinguish the nun from the physicist, I write “Sister Pauline Ott.” In the same way, I write either System.out.println or DriverManager. println. The first (which you use often) writes text on the computer’s screen. The second (which you don’t use at all in this book) 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.
94 Part II: Writing Your Own Java Programs Methods, methods everywhere Two methods play roles in the ThingsILike program. Figure 4-6 illustrates the situation, and the next few bullets give you a guided tour. Figure 4-6: Calling the System. out. println method. ✓ There’s a declaration for a main method. I wrote the main method myself. This main method is called automatically whenever I start run- ning the ThingsILike program. ✓ There’s a call to the System.out.println method. The method call for the System.out.println method is the only statement in the body of the main method. In other words, calling the System.out.println method is the only thing on the main method’s to-do list. The declaration for the System.out.println method is buried inside the official Java API. For a refresher on the Java API, refer to Chapter 1. When I say things like “System.out.println is buried inside the API,” I’m not doing justice to the API. True, you can ignore all the nitty-gritty Java code inside the API. All you need to remember is that System.out.println is defined somewhere inside that code. But I’m not being fair when I make the API code sound like something magical. The API is just another bunch of Java code. The statements in the API that tell the computer what it means to carry out a call to System.out.println look a lot like the Java code in Listing 4-1.
95Chapter 4: Exploring the Parts of a Program The Java class Have you 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 pro- gramming. 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. You can’t do anything in Java until you’ve created a class of some kind. It’s like being on Jeopardy, hearing Alex Trebek say, “Let’s go to a commercial” and then interrupting him by saying, “I’m sorry, Alex. You can’t issue an instruction without putting your instruction inside a class.” It’s important for you to understand what a class really is, so I dare not give a haphazard explanation in this chapter. Instead, I devote much of Chapter 17 to the question, “What is a class?” Anyway, in Java, your main method has to be inside a class. I wrote the code in Listing 4-1, so I got to make up a name for my new class. I chose the name ThingsILike, so the code in Listing 4-1 starts with the words class ThingsILike. Take another look at Listing 4-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 though the stuff inside the ThingsILike class is in a box. (Refer to Figure 4-3.) 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.
96 Part II: Writing Your Own Java Programs
Chapter 5 Composing a Program In This Chapter ▶ Reading input from the keyboard ▶ Editing a program ▶ Shooting at trouble Just yesterday, I was chatting with my servant, RoboJeeves. (RoboJeeves is an upscale model in the RJ-3000 line of personal robotic life-forms.) Here’s how the discussion went: Me: RoboJeeves, tell me the velocity of an object after it’s been falling for three seconds in a vacuum. RoboJeeves: All right, I will. “The velocity of an object after it’s been falling for three seconds in a vacuum.” There, I told it to you. Me: RoboJeeves, don’t give me that smart-alecky answer. I want a number. I want the actual velocity. RoboJeeves: Okay! “A number; the actual velocity.” Me: RJ, these cheap jokes are beneath your dignity. Can you or can’t you tell me the answer to my question? RoboJeeves: Yes. Me: “Yes,” what? RoboJeeves: Yes, I either can or can’t tell you the answer to your question. Me: Well, which is it? Can you? RoboJeeves: Yes, I can. Me: Then do it. Tell me the answer. RoboJeeves: The velocity is 153,984,792 miles per hour. Me: (After pausing to think . . .) RJ, I know you never make a mistake, but that number, 153,984,792, is much too high.
98 Part II: Writing Your Own Java Programs RoboJeeves: Too high? That’s impossible. Things fall very quickly on the giant planet Mangorrrrkthongo. Now, if you wanted to know about objects falling on Earth, you should have said so in the first place. Sometimes that robot rubs me the wrong way. The truth is, RoboJeeves does whatever I tell him to do — nothing more and nothing less. If I say “Feed the cat,” then RJ says, “Feed it to whom? Which of your guests will be having cat for dinner?” Computers Are Stupid Handy as they are, all computers do the same darn thing. They do exactly what you tell them to do, and that’s sometimes very unfortunate. For exam- ple, in 1962, a Mariner spacecraft to Venus was destroyed just four minutes after its launch. Why? It was destroyed because of a missing keystroke in a FORTRAN program. Around the same time, NASA scientists caught an error that could have trashed the Mercury space flights. (Yup! These were flights with people on board!) The error was a line with a period instead of a comma. (A computer programmer wrote DO 10 I=1.10 instead of DO 10 I=1,10.) With all due respect to my buddy RoboJeeves, he and his computer cousins are all incredibly stupid. Sometimes they look as though they’re second- guessing us humans, but actually they’re just doing what other humans told them to do. They can toss virtual coins and use elaborate schemes to mimic creative behavior, but they never really think on their own. If you say, “Jump,” they do what they’re programmed to do in response to the letters J-u-m-p. So when you write a computer program, you have to imagine that a genie has granted you three wishes. Don’t ask for eternal love because, if you do, then the genie will give you a slobbering, adoring mate — someone that you don’t like at all. And don’t ask for a million dollars unless you want the genie to turn you into a bank robber. Everything you write in a computer program has to be very precise. Take a look at an example. . . . A Program to Echo Keyboard Input Listing 5-1 contains a small Java program. The program lets you type one line of characters on the keyboard. As soon as you press Enter, the program d isplays a second line that copies whatever you typed.
99Chapter 5: Composing a Program Listing 5-1: A Java Program import java.util.Scanner; class EchoLine { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); System.out.println(keyboard.nextLine()); keyboard.close(); } } Most of the programs in this book are text-based programs. These programs do their input and output almost exclusively in Eclipse’s Console view. You can see GUI versions of the program in Listing 5-1, and of many other exam- ples from this book, by visiting the book’s website (http://allmycode. com/BeginProg). Figure 5-1 shows a run of the EchoLine code (the code in Listing 5-1). The text in the figure is a mixture of my own typing and the computer’s responses. Figure 5-1: What part of the word “don’t” do you not understand? In Figure 5-1, I type the first line (the first Please don’t repeat this to anyone line), and the computer displays the second line. Here’s what happens when you run the code in Listing 5-1: 1. At first, the computer does nothing. The computer is waiting for you to type something. 2. You click inside Eclipse’s Console view. As a result, you see a cursor on the left edge of Eclipse’s Console view, as shown in Figure 5-2.
100 Part II: Writing Your Own Java Programs Figure 5-2: The computer waits for you to type something. 3. You type one line of text — any text at all (see Figure 5-3). Figure 5-3: You type a sentence. 4. You press Enter, and the computer displays another copy of the line that you typed, as shown in Figure 5-4. Figure 5-4: The computer echoes your input. After displaying a copy of your input, the program’s run comes to an end. Typing and running a program This book’s website (http://allmycode.com/BeginProg) has a link for downloading all the book’s Java programs. After you download the pro- grams, you can follow instructions in Chapter 2 to add the programs to your Eclipse workspace. Then, to test the code in Listing 5-1, you can run the readymade 05-01 project.
101Chapter 5: Composing a Program But instead of running the readymade code, I encourage you to start from scratch — to type Listing 5-1 yourself and then to test your newly created code. Just follow these steps: 1. Launch Eclipse. 2. From Eclipse’s menu bar, choose File➪New➪Java Project. Eclipse’s New Java Project dialog box appears. 3. In the dialog box’s Project Name field, type MyNewProject. 4. Click Finish. Clicking Finish brings you back to the Eclipse workbench, with MyNewProject in the Package Explorer. The next step is to create a new Java source code file. 5. In the Package Explorer, select MyNewProject and then, in Eclipse’s main menu, choose File➪New➪Class. Eclipse’s New Java Class dialog box appears. 6. In the New Java Class dialog box’s Name field, type the name of your new class. In this example, use the name EchoLine. Spell EchoLine exactly the way I spell it in Listing 5-1, with a capital E, a capital L, and no blank space. In Java, consistent spelling and capitalization are very important. If you’re not consistent within a particular program, the program will probably have some nasty, annoying compile-time errors. Optionally, you can put a check mark in the box labeled public static void main(String[] args}. If you leave the box unchecked, you’ll have a bit more typing to do when you get to Step 8. Either way (checked or unchecked), it’s no big deal. 7. Click Finish. Clicking Finish brings you back to the Eclipse workbench. An editor in this workbench has a tab named EchoLine.java. 8. Type the program of Listing 5-1 in the EchoLine.java editor. Copy the code exactly as you see it in Listing 5-1. • Spell each word exactly the way I spell it in Listing 5-1. • Capitalize each word exactly the way I do in Listing 5-1. • Include all the punctuation symbols — the dots, the semicolons, everything. • Double-check the spelling of the word println. Make sure that each character in the word println is a lowercase letter. (In particular, the l in ln is a letter, not a digit.)
102 Part II: Writing Your Own Java Programs The name println comes from the words “print a line.” If you were allowed to write the name in uppercase letters, it would be PRINTLN, with a letter L near the end of the word. (Unfortunately, Java is case- sensitive. So you have to type println, which might look as though it contains a digit 1. It doesn’t.) If you typed everything correctly, you don’t see any error markers in the editor. If you see error markers, go back and compare everything you typed with the stuff in Listing 5-1. Compare every letter, every word, every squiggle, every smudge. If you’re reading an electronic version of this book, you might try copy- ing directly from Listing 5-1 and pasting it into Eclipse’s editor. This might be okay, but you might also find that the book’s electronic image contains characters that don’t belong in a Java program. For example, many books use curly quotation marks (“ and ”), which are different from Java’s straight quotation mark (\"). And remember, you can download bona fide electronic copies of the examples in this book by visiting the book’s website, http://allmycode.com/BeginProg. 9. Make any changes or corrections to the code in the editor. When at last you see no error markers, you’re ready to run the program. 10. Select the EchoLine class either by clicking inside the editor or by clicking the MyNewProject branch in the Package Explorer. 11. In Eclipse’s main menu, choose Run➪Run As➪Java Application. Your new Java program runs, but nothing much happens. 12. Click inside Eclipse’s Console view. As a result, a cursor sits on the left edge of Eclipse’s Console view. (Refer to Figure 5-2.) The computer is waiting for you to type something. If you forget to click inside the Console view, Eclipse may not send your keystrokes to the running Java program. Instead, Eclipse may send your keystrokes to the editor or (strangely enough) to the Package Explorer. 13. Type a line of text and then press Enter. In response, the computer displays a second copy of your line of text. Then the program’s run comes to an end. (Refer to Figure 5-4.) If this list of steps seems a bit sketchy, you can find much more detail in Chapter 3. (Look first at the section in Chapter 3 about compiling and run- ning a program.) For the most part, the steps here in Chapter 5 are a quick summary of the material in Chapter 3. The big difference is that in Chapter 3, I don’t encourage you to type the program yourself.
103Chapter 5: Composing a Program So what’s the big deal when you type the program yourself? Well, lots of inter- esting things can happen when you apply fingers to keyboard. That’s why the second half of this chapter is devoted to troubleshooting. How the EchoLine program works When you were a tiny newborn, resting comfortably in your mother’s arms, she told you how to send characters to the computer screen: System.out.println(whatever text you want displayed); What she didn’t tell you was how to fetch characters from the computer keyboard. There are lots of ways to do it, but the one I recommend in this chapter is keyboard.nextLine() Now, here’s the fun part. Calling the nextLine method doesn’t just scoop characters from the keyboard. When the computer runs your program, the computer substitutes whatever you type on the keyboard in place of the text keyboard.nextLine(). To understand this, look at the statement in Listing 5-1: System.out.println(keyboard.nextLine()); When you run the program, the computer sees your call to nextLine and stops dead in its tracks. (Refer to Figure 5-2.) The computer waits for you to type a line of text. So (refer to Figure 5-3) you type this line: Hey, there's an echo in here. The computer substitutes this entire Hey line for the keyboard.nextLine() call in your program. The process is illustrated in Figure 5-5. The call to keyboard.nextLine() is nestled inside the System.out. println call. So when all is said and done, the computer behaves as though the statement in Listing 5-1 looks like this: System.out.println(\"Hey, there's an echo in here.\"); The computer displays another copy of the text Hey, there's an echo in here. on the screen. That’s why you see two copies of the Hey line in Figure 5-4.
104 Part II: Writing Your Own Java Programs Figure 5-5: The c omputer substitutes text in place of the nextLine call. Getting numbers, words, and other things In Listing 5-1, the words keyboard.nextLine() get an entire line of text from the computer keyboard. So if you type Testing 1 2 3 the program in Listing 5-1 echoes back your entire Testing 1 2 3 line of text. Sometimes you don’t want a program to get an entire line of text. Instead, you want the program to get a piece of a line. For example, when you type 1 2 3, you may want the computer to get the number 1. (Maybe the number 1 stands for one customer or something like that.) In such situations, you don’t put keyboard.nextLine() in your program. Instead, you use keyboard.nextInt(). Table 5-1 shows you a few variations on the keyboard.next business. Unfortunately, the table’s entries aren’t very predictable. To read a line of input, you call nextLine. But to read a word of input, you don’t call nextWord. (The Java API has no nextWord method.) Instead, to read a word, you call next.
105Chapter 5: Composing a Program Table 5-1 Some Scanner Methods To Read This . . . . . . Make This Method Call A number with no decimal point in it nextInt() A number with a decimal point in it nextDouble() A word (ending in a blank space, for next() example) A line (or what remains of a line after nextLine() you’ve already read some data from the line) findWithinHorizon(\".\",0). A single character (such as a letter, a charAt(0) digit, or a punctuation character) Also, the table’s story has a surprise ending. To read a single character, you don’t call nextSomething. Instead, you can call the bizarre findWithin Horizon(\".\",0).charAt(0) combination of methods. (You’ll have to excuse the folks who created the Scanner class. They created Scanner from a specialized point of view.) To see some of the table’s methods in action, check other program listings in this book. Chapters 6, 7, and 8 have some particularly nice examples. Type three lines of code and don’t look back Buried innocently inside Listing 5-1 are three extra lines of code. These lines help the computer read input from the keyboard. The three lines are import java.util.Scanner; Scanner keyboard = new Scanner(System.in); keyboard.close(); Concerning these three lines, I have bad news and good news. ✓ The bad news is, the reasoning behind these lines is difficult to under- stand. That’s especially true here in Chapter 5, where I introduce Java’s most fundamental concepts. ✓ The good news is, you don’t have to understand the reasoning behind these three lines. You can copy and paste these lines into any pro- gram that gets input from the keyboard. You don’t have to change the lines in any way. These lines work without any modifications in all kinds of Java programs.
106 Part II: Writing Your Own Java Programs A quick look at the Scanner In this chapter, I advise you to ignore any use readingThingie (or any other of the meanings behind the lines import name you want to use as long as you use java.util.Scanner and Scanner the name consistently). So, if you want to keyboard, etc. Just paste these two lines be creative, you can write mindlessly in your code and then move on. Of course, you may not want to take my advice. Scanner readingThingie = You may not like ignoring things in your code. new Scanner(System.in); If you happen to be such a stubborn person, I have a few quick facts for you. System.out.println ✓ The word Scanner is defined in the (readingThingie.nextLine()); Java API. The revised Listing 5-1 (with reading A Scanner is something you can use for Thingie instead of keyboard) com- piles and runs without a hitch. getting input. This Scanner class belongs to Java ver- ✓ The line import java.util.Scanner is an example of an import declaration. sions 5.0 and higher. If you use version Java 1.4.2, you don’t have access to the An optional import declaration allows you Scanner class. (You see an error marker to abbreviate names in the rest of your pro- when you type Listing 5-1.) gram. You can remove the import declara- ✓ The words System and in are defined in tion from Listing 5-1. But if you do, you must the Java API. use the Scanner class’s fully qualified Taken together, the words System.in name throughout your code. Here’s how: stand for the computer keyboard. In later chapters, you see things like new class EchoLine { Scanner(new File(\"myData. txt\")). In those chapters, I replace public static void main System.in with the words new (String args[]) { File(\"myData.txt\") because I’m not getting input from the keyboard. java.util.Scanner keyboard Instead, I’m getting input from a file on the = new java.util.Scanner computer’s hard drive. (System.in); ✓ The word keyboard doesn’t come from the Java API. System.out.println The word keyboard is a Barry Burd (keyboard.nextLine()); creation. Instead of keyboard, you can keyboard.close(); } }
107Chapter 5: Composing a Program Just be sure to put these lines in the right places: ✓ Make the import java.util.Scanner line the first line in your program. ✓ Put the Scanner keyboard = new Scanner(System.in) line inside your main method immediately after the public static void main(String args[]) { line. ✓ Make the keyboard close() line the last line in your program. At some point in the future, you may have to be more careful about the posi- tioning of these three lines. But for now, the rules I give will serve you well. Expecting the Unexpected Not long ago, I met an instructor with an interesting policy. He said, “Sometimes when I’m lecturing, I compose a program from scratch on the computer. I do it right in front of my students. If the program compiles and runs correctly on the first try, I expect the students to give me a big round of applause.” At first, you may think this guy has an enormous ego, but you have to put things in perspective. It’s unusual for a program to compile and run correctly the first time. There’s almost always a typo or another error of some kind. So this section deals with the normal, expected errors that you see when you compile and run a program for the first time. Everyone makes these mistakes, even the most seasoned travelers. The key is keeping a cool head. Here’s my general advice: ✓ Don’t expect a program that you type to compile the first time. Be prepared to return to your editor and fix some mistakes. ✓ Don’t expect a program that compiles flawlessly to run correctly. Even with no error markers in Eclipse’s editor, your program might still contain flaws. After Eclipse compiles your program, you still have to run the program successfully. That is, your program should finish its run and display the correct output. You compile and then you run. Getting a program to compile without errors is the easier of the two tasks. ✓ Read what’s in the Eclipse editor, not what you assume is in the Eclipse editor. Don’t assume that you’ve typed words correctly, that you’ve capitalized words correctly, or that you’ve matched curly braces or parentheses correctly. Compare the code you typed with any sample code that you have. Make sure that every detail is in order.
108 Part II: Writing Your Own Java Programs ✓ Be patient. Every good programming effort takes a long time to get right. If you don’t understand something right away, be persistent. Stick with it (or put it away for a while and come back to it). There’s nothing you can’t understand if you put in enough time. ✓ Don’t become frustrated. Don’t throw your pie crust. Frustration (not lack of knowledge) is your enemy. If you’re frustrated, you can’t accomplish anything. ✓ Don’t think you’re the only person who’s slow to understand. I’m slow, and I’m proud of it. (Melba, Chapter 6 will be a week late.) ✓ Don’t be timid. If your code isn’t working and you can’t figure out why it’s not working, then ask someone. Post a message on an online forum. And don’t be afraid of anyone’s snide or sarcastic answer. (For a list of gestures you can make in response to peoples’ snotty answers, see Appendix Z.) To ask me directly, send me an e-mail message, tweet me, or post to me on Facebook. (Send e-mail to [email protected], tweets to @allmycode, or posts to Facebook at /allmycode.) Diagnosing a problem The “Typing and running a program” section, earlier in this chapter, tells you how to run the EchoLine program. If all goes well, your screen ends up looking like the one shown in Figure 5-1. But things don’t always go well. Sometimes your finger slips, inserting a typo into your program. Sometimes you ignore one of the details in Listing 5-1, and you get a nasty error message. Of course, some things in Listing 5-1 are okay to change. Not every word in Listing 5-1 is cast in stone. So here’s a nasty wrinkle — I can’t tell you that you must always retype Listing 5-1 exactly as it appears. Some changes are okay; others are not. Keep reading for some “f’rinstances.” Case sensitivity Java is case-sensitive. Among other things, case-sensitive means that, in a Java program, the letter P isn’t the same as the letter p. If you send me some fan mail and start with “Dear barry” instead of “Dear Barry,” I still know what you mean. But Java doesn’t work that way.
109Chapter 5: Composing a Program So change just one character in a Java program and instead of an uneventful compilation, you get a big headache! Change p to P like so: //The following line is incorrect: System.out.Println(keyboard.nextLine()); When you type the program in Eclipse’s editor, you get the ugliness shown in Figure 5-6. Figure 5-6: The Java compiler understands println, but not Println. When you see error markers and quick fixes like the ones in Figure 5-6, your best bet is to stay calm and read the messages carefully. Sometimes, the messages contain useful hints. (Of course, sometimes they don’t.) The message in Figure 5-6 is The method Println(String) is undefined for the type PrintStream. In plain English, this means “The Java com- piler can’t interpret the word Println.” (The message stops short of saying, “Don’t type the word Println, you Dummy!” In any case, if the computer says you’re one of us Dummies, you should take it as a compliment.) Now, there are plenty of reasons why the compiler may not be able to understand a word like Println. But, for a beginning programmer, you should check two important things right away: ✓ Have you spelled the word correctly? Did you accidentally type printlin (with a digit 1) instead of println? ✓ Have you capitalized all letters correctly? Did you incorrectly type Println or PrintLn instead of println? Either of these errors can send the Java compiler into a tailspin. So compare your typing with the approved typing word for word (and letter for letter). When you find a discrepancy, go back to the editor and fix the problem. Then try compiling the program again.
110 Part II: Writing Your Own Java Programs As you type a program in Eclipse’s editor, Eclipse tries to compile the program. When Eclipse finds a compile-time error, the editor usually displays at least three red error markers (see Figure 5-6). The marker in the editor’s left margin has an X-like marking and sometimes a tiny light bulb. The marker in the right margin is a small rectangle. The marker in the middle is a jagged red underline. If you hover your mouse over any of these markers, Eclipse displays a mes- sage that attempts to describe the nature of the error. If you hover over the jagged line, Eclipse displays a message and possibly a list of suggested solutions. (Each suggested solution is called a quick fix.) If you right-click the left margin’s marker (or control-click on a Mac) and choose Quick Fix in the resulting context menu, Eclipse displays the suggested solutions. To have Eclipse modify your code automatically (using a suggestion from the quick-fix list), either single-click or double-click the item in the quick-fix list. (That is, single-click anything that looks like a link; double-click anything that doesn’t look like a link.) Omitting punctuation In English and in Java, using the; proper! punctuation is important) Take, for example, the semicolons in Listing 5-1. What happens if you forget to type a semicolon? //The following code is incorrect: System.out.println(keyboard.nextLine()) } If you leave off the semicolon, you get the message shown in Figure 5-7. Figure 5-7: A helpful error message. A message like the one in Figure 5-8 makes your life much simpler. I don’t have to explain the message, and you don’t have to puzzle over the message’s meaning. Just take the message insert \";\" to complete Statement on its face value. Insert the semicolon between the end of the System.out. println(keyboard.nextLine()) statement and whatever code comes after the statement. (For code that’s easier to read and understand, tack on the semicolon at the end of the System.out.println(keyboard.nextLine()) statement.)
111Chapter 5: Composing a Program Figure 5-8: An unwanted semicolon messes things up. Using too much punctuation In junior high school, my English teacher said I should use a comma when- ever I would normally pause for a breath. This advice doesn’t work well during allergy season, when my sentences have more commas in them than words. Even as a paid author, I have trouble deciding where the commas should go, so I often add extra commas for good measure. This makes more work for my copy editor, Melba, who has a trash can full of commas by the desk in her office. It’s the same way in a Java program. You can get carried away with punctuation. Consider, for example, the main method header in Listing 5-1. This line is a dangerous curve for novice programmers. For information on the terms method header and method body, refer to Chapter 4. Why can’t the computer fix it? How often do you get to finish someone else’s The answer is simple. The computer isn’t inter- sentence? “Please,” says your supervisor, “go ested in taking any chances. What if you don’t over there and connect the . . . ” really want a semicolon after the statement on “Wires,” you say. “I’ll connect the wires.” If you line 8? What if the missing semicolon repre- know what someone means to say, why wait for sents a more profound problem? If the computer them to say it? added the extra semicolon, it could potentially This same question comes up in connection with do more harm than good. computer error messages. Take a look at the Returning to you and your supervisor . . . message in Figure 5-7. The computer expects Boom! A big explosion. “Not the wires, you a semicolon after the statement on line 8. Well, Dummy. The dots. I wanted you to connect the Mr. Computer, if you know where you want a dots.” semicolon, then just add the semicolon and be “Sorry,” you say. done with it. Why are you bothering me about it?
112 Part II: Writing Your Own Java Programs Normally, you shouldn’t be ending a method header with a semicolon. But people add semicolons anyway. (Maybe, in some subtle way, a method header looks like it should end with a semicolon.) //The following line is incorrect: public static void main(String args[]); { If you add this extraneous semicolon to the code in Listing 5-1, you get the message shown in Figure 5-8. The error message and quick fixes in Figure 5-8 are a bit misleading. The message starts with This method requires a body. But the method has a body. Doesn’t it? When the computer tries to compile public static void main(String args[]); (ending with a semicolon), the computer gets confused. I illustrate the confusion in Figure 5-9. Your eye sees an extra semicolon, but the com- puter’s eye interprets this as a method without a body. So that’s the error message — the computer says This method requires a body instead of a semicolon. Figure 5-9: What’s on this computer’s mind?
113Chapter 5: Composing a Program If you select the Add Body quick fix, Eclipse creates the following (really horrible) code: import java.util.Scanner; class EchoLine { public static void main(String args[]) { }{ Scanner keyboard = new Scanner(System.in); System.out.println(keyboard.nextLine()); keyboard.close(); } } This “fixed” code has no compile-time errors. But when you run this code, nothing happens. The program starts running and then stops running with nothing in Eclipse’s Console view. We all know that a computer is a very patient, very sympathetic machine. That’s why the computer looks at your code and decides to give you one more chance. The computer remembers that Java has an advanced feature in which you write a method header without writing a method body. When you do this, you get what’s called an abstract method — something that I don’t use at all in this book. Anyway, in Figure 5-9, the computer sees a header with no body. So the computer says to itself, “I know! Maybe the programmer is trying to write an abstract method. The trouble is, an abstract method’s header has to have the word abstract in it. I should remind the program- mer about that.” So the computer offers the add 'abstract' modifier quick fix in Figure 5-9. One way or another, you can’t interpret the error message and the quick fixes in Figure 5-9 without reading between the lines. So here are some tips to help you decipher murky messages: ✓ Avoid the knee-jerk response. Some people see the add 'abstract' modifier quick fix in Figure 5-9 and wonder where they can add a modifier. Unfortunately, this isn’t the right approach. If you don’t know what an 'abstract' modifier is, then chances are you didn’t mean to use an abstract modifier in the first place. ✓ Stare at the bad line of code for a long, long time. If you look carefully at the public static . . . line in Figure 5-9, eventually you’ll notice that it’s different from the corresponding line in Listing 5-1. The line in Listing 5-1 has no semicolon, but the line in Figure 5-9 has one.
114 Part II: Writing Your Own Java Programs Of course, you won’t always be starting with some prewritten code like the stuff in Listing 5-1. That’s where practice makes perfect. The more code you write, the more sensitive your eyes will become to things like extraneous semicolons and other programming goofs. Too many curly braces You’re looking for the nearest gas station, so you ask one of the locals. “Go to the first traffic light and make a left,” says the local. You go straight for a few streets and see a blinking yellow signal. You turn left at the signal and travel for a mile or so. What? No gas station? Maybe you mistook the blinking signal for a real traffic light. You come to a fork in the road and say to yourself, “The directions said noth- ing about a fork. Which way should I go?” You veer right, but a minute later, you’re forced onto a highway. You see a sign that says, Next Exit 24 Miles. Now you’re really lost, and the gas gauge points to “S.” (The “S” stands for “Stranded.”) So here’s what happened: You made an honest mistake. You shouldn’t have turned left at the yellow blinking light. That mistake alone wasn’t so terrible. But that first mistake lead to more confusion, and eventually, your choices made no sense at all. If you hadn’t turned at the blinking light, you’d never have encountered that stinking fork in the road. Then getting on the highway was sheer catastrophe. Is there a point to this story? Of course there is. A computer can get itself into the same sort of mess. The computer notices an error in your program. Then, metaphorically speaking, the computer takes a fork in the road — a fork based on the original error — a fork for which none of the alternatives leads to good results. Here’s an example. You’re retyping the code in Listing 5-1, and you mistakenly type an extra curly brace: //The following code is incorrect: import java.util.Scanner; class EchoLine { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); } System.out.println(keyboard.nextLine()); } keyboard.close(); }
115Chapter 5: Composing a Program In Eclipse’s editor, you hover over the leftmost marker. You see the messages shown in Figure 5-10. Figure 5-10: Three error messages. Eclipse is confused because the call to System.out.println is completely out of place. Eclipse displays three messages — something about println, something about the parenthesis, and something very cryptic concerning misplaced constructs. None of these messages addresses the cause of the problem. Eclipse is trying to make the best of a bad situation, but at this point, you shouldn’t believe a word that Eclipse says. Computers aren’t smart animals, and if someone programs Eclipse to say misplaced construct(s), that’s exactly what Eclipse says. (Some people say that computers make them feel stupid. For me, it’s the opposite. A com- puter reminds me how dumb a machine can be and how smart a person can be. I like that.) So when you see a bunch of error messages, read each error message care- fully. Ask yourself what you can learn from each message. But don’t take each message as the authoritative truth. When you’ve exhausted your efforts with Eclipse’s messages, return to your efforts to stare carefully at the code. If you get more than one error message, always look carefully at each message in the bunch. Sometimes a very helpful message hides among a bunch of not-so-helpful messages. Misspelling words (and other missteps) You’ve found an old family recipe for deviled eggs (one of my favorites). You follow every step as carefully as you can, but you leave out the salt because of your grandmother’s high blood pressure. You hand your grandmother an egg (a finished masterpiece). “Not enough pepper,” she says, and she walks away. The next course is beef bourguignon. You take an unsalted slice to dear old Granny. “Not sweet enough,” she groans, and she leaves the room. “But that’s impossible,” you think. “There’s no sugar in beef bourguignon. I left out the salt.” Even so, you go back to the kitchen and prepare mashed potatoes. You use unsalted butter, of course. “She’ll love it this time,” you think.
116 Part II: Writing Your Own Java Programs “Sour potatoes! Yuck!” Granny says, as she goes to the sink to spit it all out. Because you have a strong ego, you’re not insulted by your grandmother’s behavior. But you’re somewhat confused. Why is she saying such different things about three unsalted recipes? Maybe there are some subtle differences that you don’t know about. Well, the same kind of thing happens when you’re writing computer programs. You can make the same kind of mistake twice (or at least, make what you think is the same kind of mistake twice) and get different error messages each time. For example, if you change the spelling or capitalization of println in Listing 5-1, Eclipse tells you the method is undefined for the type PrintStream. But if you change System to system, Eclipse says that system cannot be resolved. And with System misspelled, Eclipse doesn’t notice whether println is spelled correctly or not. In Listing 5-1, if you change the spelling of args, nothing goes wrong. The program compiles and runs correctly. But if you change the spelling of main, you face some unusual difficulties. (If you don’t believe me, read the “Runtime error messages” section, later in this chapter.) Still in Listing 5-1, change the number equal signs in the Scanner keyboard = new Scanner(System.in) line. With one equal sign, everybody’s happy. If you accidentally type two equal signs (Scanner keyboard == new Scanner(System.in)), Eclipse steers you back on course, telling you Syntax error on token \"==\", = expected (see Figure 5-11). But if you go crazy and type four equal signs or if you type no equal signs at all, Eclipse misinterprets everything and suggests that you insert \";\" to complete BlockStatements. Unfortunately, inserting a semicolon is no help at all (see Figure 5-12). Figure 5-11: Remove the second of two equal signs. So remember: Java responds to errors in many different ways. Two changes in your code might look alike, but similar changes don’t always lead to similar results. Each problem in your code requires its own individualized attention.
117Chapter 5: Composing a Program Figure 5-12: You’re missing an equal sign, but Eclipse fails to notice. Here’s a useful exercise: Start with a working Java program. After successfully running the code, make a change that intentionally introduces errors. Look carefully at each error message and ask yourself whether the message would help you diagnose the problem. This exercise is great because it helps you think of errors as normal occurrences and gives you practice analyzing messages when you’re not under pressure to get your program to run correctly. Runtime error messages Up to this point in the chapter, I describe errors that crop up when you com- pile a program. Another category of errors hides until you run the program. A case in point is the improper spelling or capitalization of the word main. Assume that, in a moment of wild abandon, you incorrectly spell main with a capital M: //The following line is incorrect: public static void Main(String args[]) { When you type the code, everything is hunky-dory. You don’t see any error markers. But then you try to run your program. At this point, the bits hit the fan. The catastrophe is illustrated in Figure 5-13. Figure 5-13: Whadaya mean “Main method not found in class EchoLine?”
118 Part II: Writing Your Own Java Programs Sure, your program has something named Main, but does it have anything named main? (Yes, I’ve heard of a famous poet named e. e. cummings, but who the heck is E. E. Cummings?) The computer doesn’t presume that your word Main means the same thing as the expected word main. You need to change Main back to main. Then everything will be okay. But in the meantime (or in the maintime), how does this improper capitaliza- tion make it past the compiler? Why don’t you get error messages when you compile the program? And if a capital M doesn’t upset the compiler, why does this capital M mess everything up at runtime? The answer goes back to the different kinds of words in the Java program- ming language. As I say in Chapter 4, Java has identifiers and keywords. The keywords in Java are cast in stone. If you change class to Class or public to Public, you get something new — something that the computer probably can’t understand. That’s why the compiler chokes on improper keyword capitalizations. It’s the compiler’s job to make sure that all the keywords are used properly. On the other hand, the identifiers can bounce all over the place. Sure, there’s an identifier named main, but you can make up a new identifier named Main. (You shouldn’t do it, though. It’s too confusing to people who know Java’s usual meaning for the word main.) When the compiler sees a mistyped line, like public static void Main, the compiler just assumes that you’re making up a brand-new name. So the compiler lets the line pass. You get no complaints from your old friend, the compiler. But then, when you try to run the code, the computer goes ballistic. The Java Virtual Machine (JVM) runs your code. (For details, see Chapter 1.) The JVM needs to find a place to start executing statements in your code, so the JVM looks for a starting point named main, with a small m. If the JVM doesn’t see anything named main, the JVM gets upset. “Main method not found in class EchoLine,” says the JVM. So at runtime, the JVM, and not the compiler, gives you an error message. A better error message would be main method not found in class EchoLine, with a lowercase letter m in main. Here and there, the people who create the error messages overlook a detail or two. What problem? I don’t see a problem I end this chapter on an upbeat note by showing you some of the things you can change in Listing 5-1 without rocking the boat.
119Chapter 5: Composing a Program The identifiers that you create If you create an identifier, then that name is up for grabs. For example, in Listing 5-1, you can change EchoLine to RepeatAfterMe. class RepeatAfterMe { public static void main ... etc. This presents no problem at all, as long as you’re willing to be consistent. Just follow most of the steps in this chapter’s earlier “Typing and running a program” section. ✓ In Step 6, instead of typing EchoLine, type RepeatAfterMe in the New Java Class dialog box’s Name field. ✓ In Step 8, when you copy the code from Listing 5-1, don’t type class EchoLine { near the top of the listing. Instead, type the words class RepeatAfterMe { Spaces and indentation Java isn’t fussy about the use of spaces and indentation. All you need to do is keep your program well-organized and readable. Here’s an alternative to spacing and indentation of the code in Listing 5-1: import java.util.Scanner; class EchoLine { public static void main( String args[] ) { Scanner keyboard = new Scanner( System.in ); System.out.println ( keyboard.nextLine() ); keyboard.close(); } } How you choose to do things A program is like a fingerprint. No two programs look very much alike. Say that I discuss a programming problem with a colleague. Then we go our separate ways and write our own programs to solve the same problem. Sure, we’re duplicating the effort. But will we create the exact same code? Absolutely not. Everyone has his or her own style, and everyone’s style is unique.
120 Part II: Writing Your Own Java Programs I asked fellow Java programmer David Herst to write his own EchoLine program without showing him my code from Listing 5-1. Here’s what he wrote: import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class EchoLine { public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String input = br.readLine(); System.out.println(input); } } Don’t worry about BufferedReader, InputStreamReader, or things like that. Just notice that, like snowflakes, no two programs are written exactly alike, even if they accomplish the same task. That’s nice. It means your code, however different, can be as good as the next person’s. That’s very encouraging.
Chapter 6 Using the Building Blocks: Variables, Values, and Types In This Chapter ▶ Declaring variables ▶ Assigning values to variables ▶ Working with numbers ▶ Using Java types Back in 1946, John von Neumann wrote a groundbreaking paper about the newly emerging technology of computers and computing. Among other things, he established one fundamental fact: For all their complexity, the main business of computers is to move data from one place to another. Take a number — the balance in a person’s bank account. Move this number from the computer’s memory to the computer’s processing unit. Add a few dollars to the balance and then move it back to the computer’s memory. The movement of data . . . that’s all there is; there ain’t no more. Good enough! This chapter shows you how to move around your data. Using Variables Here’s an excerpt from a software company’s website: SnitSoft recognizes its obligation to the information technology com- munity. For that reason, SnitSoft is making its most popular applications available for a nominal charge. For just $5.95 plus shipping and handling, you receive a CD-ROM containing SnitSoft’s premier products.
122 Part II: Writing Your Own Java Programs Go ahead. Click the Order Now! link. Just see what happens. You get an order form with two items on it. One item is labeled $5.95 (CD-ROM), and the other item reads $25.00 (shipping and handling). What a rip-off! Thanks to SnitSoft’s generosity, you can pay $30.95 for ten cents’ worth of software. Behind the scenes of the SnitSoft web page, a computer program does some scoundrel’s arithmetic. The program looks something like the code in Listing 6-1. Listing 6-1: SnitSoft’s Grand Scam class SnitSoft { public static void main(String args[]) { double amount; amount = 5.95; amount = amount + 25.00; System.out.print(\"We will bill $\"); System.out.print(amount); System.out.println(\" to your credit card.\"); } } When I run Listing 6-1 code on my own computer (not the SnitSoft computer), I get the output shown in Figure 6-1. Figure 6-1: Running the code from Listing 6-1. Using a variable The code in Listing 6-1 makes use of a variable named amount. A variable is a placeholder. You can stick a number like 5.95 into a variable. After you’ve placed a number in the variable, you can change your mind and put a different number, like 30.95, into the variable. (That’s what varies in a variable.) Of course, when you put a new number in a variable, the old number is no longer there. If you didn’t save the old number somewhere else, the old number is gone.
123Chapter 6: Using the Building Blocks: Variables, Values, and Types Figure 6-2 gives a before-and-after picture of the code in Listing 6-1. When the computer executes amount = 5.95, the variable amount has the number 5.95 in it. Then, after the amount = amount + 25.00 statement is executed, the variable amount suddenly has 30.95 in it. When you think about a variable, picture a place in the computer’s memory where wires and transistors store 5.95, 30.95, or whatever. In Figure 6-2, imagine that each box is s urrounded by m illions of other such boxes. Figure 6-2: A variable (before and after). Now you need some terminology. (You can follow along in Figure 6-3.) The thing stored in a variable is called a value. A variable’s value can change during the run of a program (when SnitSoft adds the shipping and handling cost, for example). The value stored in a variable isn’t necessarily a number. (You can, for example, create a variable that always stores a letter.) The kind of value stored in a variable is a variable’s type. (You can read more about types in the rest of this chapter and in the next two chapters as well.) Figure 6-3: A variable, its value, and its type.
124 Part II: Writing Your Own Java Programs There’s a subtle, almost unnoticeable difference between a variable and a variable’s name. Even in formal writing, I often use the word variable when I mean variable name. Strictly speaking, amount is the variable name, and all the memory storage associated with amount (including the value and type of amount) is the variable itself. If you think this distinction between variable and variable name is too subtle for you to worry about, join the club. Every variable name is an identifier — a name that you can make up in your own code (for more about this, see Chapter 4). In preparing Listing 6-1, I made up the name amount. Understanding assignment statements The statements with equal signs in Listing 6-1 are called assignment statements. In an assignment statement, you assign a value to something. In many cases, this something is a variable. You should get into the habit of reading assignment statements from right to left. For example, the first assignment statement in Listing 6-1 says, “Assign 5.95 to the amount variable.” The second assignment statement is just a bit more complicated. Reading the second assignment statement from right to left, you get “Add 25.00 to the value that’s already in the amount variable and make that number (30.95) be the new value of the amount variable.” For a graphic, hit-you-over-the-head illustration of this, see Figure 6-4. Figure 6-4: Reading an assignment statement from right to left. In an assignment statement, the thing being assigned a value is always on the left side of the equal sign.
125Chapter 6: Using the Building Blocks: Variables, Values, and Types To wrap or not to wrap? The last three statements in Listing 6-1 use a neat trick. You want the program to display just one line on the screen, but this line contains three different things: ✓ The line starts with We will bill $. ✓ The line continues with the amount variable’s value. ✓ The line ends with to your credit card. These are three separate things, so you put these things in three separate statements. The first two statements are calls to System.out.print. The last statement is a call to System.out.println. Calls to System.out.print display text on part of a line and then leave the cursor at the end of the current line. After executing System.out. print, the cursor is still at the end of the same line, so the next System. out.whatever can continue printing on that same line. With several calls to print capped off by a single call to println, the result is just one nice- looking line of output, as Figure 6-5 illustrates. Figure 6-5: The roles played by System. out. print and System. prinotultn.. A call to System.out.print writes some things and leaves the cursor sitting at the end of the line of output. A call to System.out.println writes things and then finishes the job by moving the cursor to the start of a brand-new line of output.
126 Part II: Writing Your Own Java Programs What Do All Those Zeros and Ones Mean? Here’s a word: gift The question for discussion is, what does that word mean? Well, it depends on who looks at the word. For example, an English-speaking reader would say that “gift” stands for something one person bestows upon another in a box covered in bright paper and ribbons. Look! I’m giving you a gift! But in German, the word “gift” means “poison.” Let me give you some gift, my dear. And in Swedish, “gift” can mean either “married” or “poison.” As soon as they got gift, she slipped a gift into his drink. Then there’s French. In France, there’s a candy bar named “Gift.” He came for the holidays, and all he gave me was a bar of Gift. So what do the letters g-i-f-t really mean? Well, they don’t mean anything until you decide on a way to interpret them. The same is true of the zeros and ones inside a computer’s circuitry. Take, for example, the sequence 01001010. This sequence can stand for the letter J, but it can also stand for the number 74. That same sequence of zeros and ones can stand for 1.0369608636003646×10–43. And when interpreted as screen pixels, the same sequence can represent the dots shown in Figure 6-6. The meaning of 01001010 depends entirely on the way the software interprets this sequence. Figure 6-6: An extreme close-up of eight black- and-white screen pixels.
127Chapter 6: Using the Building Blocks: Variables, Values, and Types Types and declarations How do you tell the computer what 01001010 stands for? The answer is in the concept called type. The type of a variable describes the kinds of values that the variable is permitted to store. In Listing 6-1, look at the first line in the body of the main method: double amount; This line is called a variable declaration. Putting this line in your program is like saying, “I’m declaring my intention to have a variable named amount in my program.” This line reserves the name amount for your use in the program. In this variable declaration, the word double is a Java keyword. This word double tells the computer what kinds of values you intend to store in amount. In particular, the word double stands for numbers between –1.8×10308 and 1.8×10308. That’s an enormous range of numbers. Without the fancy ×10 nota- tion, the second of these numbers is 180000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000.0 If the folks at SnitSoft ever charge that much for shipping and handling, they can represent the charge with a variable of type double. What’s the point? More important than the humongous range of the double keyword’s num- bers is the fact that a double value can have digits to the right of the decimal point. After you declare amount to be of type double, you can store all sorts of numbers in amount. You can store 5.95, 0.02398479, or –3.0. In Listing 6-1, if I hadn’t declared amount to be of type double, I wouldn’t have been able to store 5.95. Instead, I would have had to store plain old 5 or dreary old 6, with- out any digits beyond the decimal point. For more info on numbers without decimal points, see Chapter 7.
128 Part II: Writing Your Own Java Programs This paragraph deals with a really picky point, so skip it if you’re not in the mood. People often use the phrase “decimal number” to describe a number with digits to the right of the decimal point. The problem is, the syllable “dec” stands for the number 10, so the word “decimal” implies a base-10 representa- tion. Because computers store base-2 (not base-10) representations, the word “decimal” to describe such a number is a misnomer. But in this book, I just can’t help myself. I’m calling them “decimal numbers,” whether the techies like it or not. Reading Decimal Numbers from the Keyboard I don’t believe it! SnitSoft is having a sale! For one week only, you can get the SnitSoft CD-ROM for the low price of just $5.75! Better hurry up and order one. No, wait! Listing 6-1 has the price fixed at $5.95. I have to revise the program. I know. I’ll make the code more versatile. I’ll input the amount from the key- board. Listing 6-2 has the revised code, and Figure 6-7 shows a run of the new code. Listing 6-2: Getting a Double Value from the Keyboard import java.util.Scanner; class VersatileSnitSoft { public static void main(String args[]) { Scanner keyboard = new Scanner(System.in); double amount; System.out.print(\"What's the price of a CD-ROM? \"); amount = keyboard.nextDouble(); amount = amount + 25.00; System.out.print(\"We will bill $\"); System.out.print(amount); System.out.println(\" to your credit card.\"); keyboard.close(); } }
129Chapter 6: Using the Building Blocks: Variables, Values, and Types Figure 6-7: Getting the value of a double variable. Grouping separators vary from one country to another. The run shown in Figure 6-7 is for a computer configured in the United States where 5.75 means “five and seventy-five hundredths.” But the run might look different on a com- puter that’s configured in what I call a “comma country” — a country where 5,75 means “five and seventy-five hundredths.” If you live in a comma country, and you type 5.75 exactly as it’s shown in Figure 6-7, you probably get an error message (an InputMismatchException). If so, change the number amounts in your file to match your country’s number format. When you do, you should be okay. Though these be methods, yet there is madness in ’t Notice the call to the nextDouble method in Listing 6-2. Back in Listing 5-1, I use nextLine, but here in Listing 6-2, I use nextDouble. In Java, each type of input requires its own special method. If you’re getting a line of text, then nextLine works just fine. But if you’re reading stuff from the keyboard and you want that stuff to be interpreted as a number, you need a method like nextDouble. To go from Listing 6-1 to Listing 6-2, I added an import declaration and some stuff about new Scanner(System.in). You can find out more about these things by reading the section on input and output in Chapter 5. (You can find out even more about input and output by visiting Chapter 13.) And more exam- ples (more keyboard.nextSomething methods) are in Chapters 7 and 8. Methods and assignments Note how I use keyboard.nextDouble in Listing 6-2. The call to method keyboard.nextDouble is part of an assignment statement. If you look in Chapter 5 at the section on how the EchoLine program works, you see that
130 Part II: Writing Your Own Java Programs the computer can substitute something in place of a method call. The com- puter does this in Listing 6-2. When you type 5.75 on the keyboard, the com- puter turns amount = keyboard.nextDouble(); into amount = 5.75; (The computer doesn’t really rewrite the code in Listing 6-2. This amount = 5.75 line just illustrates the effect of the computer’s action.) In the second assignment statement in Listing 6-2, the computer adds 25.00 to the 5.75 that’s stored in amount. Some method calls have this substitution effect, and others (like System. out.println) don’t. To find out more about this topic, see Chapter 19. Who does what, and how? When you write a program, you’re called a pro- starts running, the user has to stare at the grammer, but when you run a program, you’re screen to figure out what to do next. The code called a user. So when you test your own code, in Listing 6-2 works in this stare-at-the-screen you’re being both the programmer and the user. scenario. In Listing 6-2, the first call to print Suppose that your program contains a puts an informative message (What's the keyboard.nextSomething() call, like price of a CD-ROM?) on the user’s screen. the calls in Listings 5-1 and 6-2. Then your pro- A message of this kind is called a prompt. gram gets input from the user. But, when the When you start writing programs, you can easily program runs, how does the user know to type confuse the roles of the prompt and the user’s something on the keyboard? If the user and input. So remember, no preordained relation- the programmer are the same person, and the ship exists between a prompt and the subse- program is fairly simple, then knowing what quent input. To create a prompt, you call print to type is no big deal. For example, when you or println. Then, to read the user’s input, start running the code in Listing 5-1, you have you call nextLine, nextDouble, or one of this book in front of you, and the book says the Scanner class’s other nextSomething “The computer is waiting for you to type some- methods. These print and next calls belong thing . . . You type one line of text . . . ” So you in two separate statements. Java has no com- type the text and press Enter. Everything is fine. monly used, single statement that does both the But very few programs come with their own prompting and the “next-ing.” books. In many instances, when a program
131Chapter 6: Using the Building Blocks: Variables, Values, and Types As the programmer, your job is to combine the doesn’t wait for the user to type anything. prompting and the next-ing. You can combine The program races to execute whatever prompting and next-ing in all kinds of ways. statement comes immediately after the Some ways are helpful to the user, and some print or println. ways aren’t. ✓ If your prompt displays a misleading mes- ✓ If you don’t have a call to printor sage, then you mislead the user. Java has println, then the user sees no prompt. no built-in feature that checks the appropri- A blinking cursor sits quietly and waits ateness of a prompt. That’s not surprising. for the user to type something. The user Most computer languages have no prompt- has to guess what kind of input to type. checking feature. Occasionally that’s okay, but usually it isn’t. So be careful with your prompts. Be nice to ✓ If you call print or println, but your user. Remember, you were once a humble you don’t call a keyboard.next computer user, too. Something method, then the computer Variations on a Theme In Listing 6-1, it takes two lines to give the amount variable its first value: double amount; amount = 5.95; You can do the same thing with just one line: double amount = 5.95; When you do this, you don’t say that that you’re “assigning” a value to the amount variable. The line double amount=5.95 isn’t called an “assignment statement.” Instead, this line is called a declaration with an initialization. You’re initializing the amount variable. You can do all sorts of things with ini- tializations, even arithmetic. double gasBill = 174.59; double elecBill = 84.21; double H2OBill = 22.88; double total = gasBill + elecBill + H2OBill; Moving variables from place to place It helps to remember the difference between initializations and assignments. For one thing, you can drag a declaration with its initialization outside of a method.
132 Part II: Writing Your Own Java Programs //This is okay: class SnitSoft { static double amount = 5.95; public static void main(String args[]) { amount = amount + 25.00; System.out.print(\"We will bill $\"); System.out.print(amount); System.out.println(\" to your credit card.\"); } } You can’t do the same thing with assignment statements. (See the following code and Figure 6-8.) //This does not compile: class BadSnitSoftCode { static double amount; amount = 5.95; //Misplaced statement public static void main(String args[]) { amount = amount + 25.00; System.out.print(\"We will bill $\"); System.out.print(amount); System.out.println(\" to your credit card.\"); } } Figure 6-8: A failed attempt to compile BadSnit SoftC ode.
133Chapter 6: Using the Building Blocks: Variables, Values, and Types You can’t drag statements outside of methods. (Even though a variable decla- ration ends with a semicolon, a variable declaration isn’t considered to be a statement. Go figure!) The advantage of putting a declaration outside of a method is illustrated in Chapter 19. While you wait impatiently to reach that chapter, notice how I added the word static to each declaration that I pulled out of the main method. I had to do this because the main method’s header has the word static in it. Not all methods are static. In fact, most methods aren’t static. But whenever you pull a declaration out of a static method, you have to add the word static at the beginning of the declaration. All the mystery surrounding the word static is resolved in Chapter 18. Combining variable declarations The code in Listing 6-1 has only one variable (as if variables are in short supply). You can get the same effect with several variables. class SnitSoftNew { public static void main(String args[]) { double cdPrice; double shippingAndHandling; double total; cdPrice = 5.95; shippingAndHandling = 25.00; total = cdPrice + shippingAndHandling; System.out.print(\"We will bill $\"); System.out.print(total); System.out.println(\" to your credit card.\"); } } This new code gives you the same output as the code in Listing 6-1. (Refer to Figure 6-1.) The new code has three declarations — one for each of the program’s three variables. Because all three variables have the same type (the type double), I can modify the code and declare all three variables in one fell swoop: double cdPrice, shippingAndHandling, total;
134 Part II: Writing Your Own Java Programs So which is better, one declaration or three declarations? Neither is better. It’s a matter of personal style. You can even add initializations to a combined declaration. When you do, each initialization applies to only one variable. For example, with the line double cdPrice, shippingAndHandling = 25.00, total; the value of shippingAndHandling becomes 25.00, but the variables cdPrice and total get no particular value.
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 1 - 50
- 51 - 100
- 101 - 150
- 151 - 200
- 201 - 250
- 251 - 300
- 301 - 350
- 351 - 400
- 401 - 450
- 451 - 483
Pages: