• Tidak ada hasil yang ditemukan

A QUICK LOOK AT THE SCANNER

Dalam dokumen Beginning Programming with Java (Halaman 160-166)

Make the import java.util.Scanner line the first line in your program.

Put the Scanner keyboard = new Scanner(System.in) line inside the 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 positioning of these three lines. But for now, the rules I give will serve you well.

The word keyboard doesn’t come from the Java API.

The word keyboard is a Barry Burd creation. Instead of keyboard , you can use readingThingie (or any other name you want to use as long as you use the name consistently). So, if you want to be creative, you can write

Scanner readingThingie = new Scanner(System.in);

System.out.println(readingThingie .nextLine());

The revised Listing 5-1 (with readingThingie instead of keyboard

) compiles and runs without a hitch.

The line import java.util.Scanner is an example of an import declaration .

The optional import declaration allows you to abbreviate names in the rest of your program. You can remove the import declaration from Listing 5-1 . But if you do, you must use the Scanner class’s fully qualified name throughout your code. Here’s how:

class EchoLine {

public static void main(String args[]) {

java.util.Scanner

keyboard = new java.util.Scanner (System.in);

System.out.println(keyboard.nextLine());

keyboard.close();

} }

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 it 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.

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. (Katie, 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, ask someone. Post a message in 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 email message, tweet me, or post to me on Facebook. (Send email to BeginProg@allmycode.com , 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. 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.

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 .

image

FIGURE 5-6: The Java compiler understands println , but not Println .

When you see error markers 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 compiler 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 print1n with the digit 1, instead of println

with the lowercase letter l ?

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.

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. (Refer to 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 square. The marker in the middle is a jagged red underline.

If you hover the mouse cursor over any of these markers, Eclipse displays a message 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.)

Not enough 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())

keyboard.close();

If you leave off the semicolon, you see the message shown in Figure 5-7 .

image

FIGURE 5-7: A helpful error message.

A message like the one in Figure 5-7 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 at 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.)

Dalam dokumen Beginning Programming with Java (Halaman 160-166)