• Tidak ada hasil yang ditemukan

Beginning Programming with Java

N/A
N/A
Charlie Purnomo

Academic year: 2023

Membagikan "Beginning Programming with Java"

Copied!
698
0
0

Teks penuh

If you are comfortable writing programs in a language other than Java, this book is not for you. So when you accomplish one of these platform-specific tasks, try following the steps in this book.

Getting Started with Java Programming

This book is divided into subsections, which are grouped into sections, which are grouped into chapters, which are finally grouped into five parts. After months of writing, you find yourself dreaming in paragraphs and chapters when you go to bed at night.).

Writing Your Own Java Programs

Controlling the Flow

Using Program Units

The Part of Tens

You might also find this fact useful if you plan to read other (more geeky) books about Java. If you've made it this far, you're ready to start reading about computer programming.

Getting Started with Java Programming

IN THIS PART …

Getting Started

IN THIS CHAPTER

When you see the word Start on the computer screen, the computer stores the word. You can write source code and then get the computer to generate object code from your source code.

WHAT IS BYTECODE, ANYWAY?

As the zeros and ones in Figure 1-1 trickle through the circuits of my computer, the computer "thinks" the thoughts shown in Figure 1-3. The java file (or java.exe) contains the instructions shown earlier in Figure 1-4 - Instructions in the JVM.

FIGURE 1-3: What the computer gleans from a bytecode file.
FIGURE 1-3: What the computer gleans from a bytecode file.

WRITE ONCE, RUN ANYWHERE

Instead of using Eclipse, you can use IntelliJ IDEA, NetBeans, BlueJ or any other Java IDE. In fact, you can write and run this book's programs without an IDE if you like to do so.

Setting Up Your Computer

To start writing Java programs, you need the software that I describe in Chapter 1: a Java compiler and a Java Virtual Machine (JVM for short). The software comes as three downloads: one from this book's website, another from Oracle, and a third from eclipse.org.

  • Find the icon representing the Java software that you downloaded in Step 2. Double-click the icon to begin
  • If you downloaded an .exe file in Step 4, double-click this file’s icon to begin the installation of Eclipse
  • Launch Eclipse and click the Welcome screen’s Workbench icon
  • In Eclipse, import the code that you downloaded in Step 1

Typically, the Eclipse website will automatically check your computer's operating system and offer you a download optimized for your system. If you downloaded a .zip file or a .tar.gz file in step 4, extract the contents of this compressed archive.

THOSE PESKY FILENAME EXTENSIONS

The real name of the file could be Mortgage.java , Mortgage.class , Mortgage.somethingElse or plain old mortgage. So if your files are named Mortgage instead of Mortgage.java or Mortgage.class , check the documentation specific to your Linux distribution.

COMPRESSED ARCHIVE FILES

If not, you can view the .zip file's contents by double-clicking the file's icon. In fact, you can copy the file's contents and perform other file operations after double-clicking the file's icon.).

FIGURE 2-1: Getting the Java JDK.
FIGURE 2-1: Getting the Java JDK.

EENIE, MEENIE, MINEY MO

By the way, another name for JDK is Java SDK - Java Software Development Kit. But if you're not sure, skip the Java EE and Java ME links.

HOW MANY BITS DOES YOUR COMPUTER HAVE?

Choose Apple ⇒   About This Mac

In the About This Mac dialog that appears, look for the word Version

If you don't trust Table 2-1 (and frankly, you shouldn't trust everything you find in print), you can run tests on your computer to detect the presence of Java and (if your Mac has Java) The Java version number.

In the Spotlight’s search field, type Java Preferences

When the Spotlight’s top hit is Java Preferences, press Enter

The Java Preferences window lists versions of Java that are installed on your computer

On the Apple menu, select System Preferences

In the System Preferences application window, click the Java icon

If your Java Control Panel looks like the panel in Figure 2- 4 , you see your computer’s Java version on the panel’s

If your Java Control Panel looks like the panel in Figure 2-5, select the Java tab of the panel.

On the Java tab, click View

Look for versions of Java on the User tab and the System tab of the Java Runtime Environment Settings window

Poke around among the desktop’s menus for something named Terminal (also known as Konsole)

In the Terminal window, type the following text and then press Enter: java -version

However, if your computer answers with the number 9 or higher, you can pop open the champagne and wait for some good times using the examples in this book. In the previous sections, you get all the tools your computer needs for processing Java programs.

Click the Download button

Click the button to download the current Eclipse version

Click the appropriate button and follow the appropriate links to get the download to begin

If you are downloading Eclipse to use on another computer, you may want to override the automatic operating system selection. If you know which version of Java you have (32-bit or 64-bit), be sure to download the appropriate version of Eclipse.

FIGURE 2-8: The home page for eclipse.org.
FIGURE 2-8: The home page for eclipse.org.

Launch Eclipse

In the Workspace Launcher dialog box, click OK to accept the default (or don't accept the default!).

In the Workspace Launcher dialog, click OK to accept the default (or don’t accept the default!)

On the Welcome screen, look for a button or an icon labeled Workbench

Click the Workbench icon to open Eclipse’s main screen

Eclipse normally searches your computer for Java installations and selects an installed version of Java to use to run your Java. Your computer may have more than one version of Java, so you may want to double-check Eclipse's choice of Java version. In the tree on the left of the Preferences dialog box, expand the Java branch.

FIGURE 2-10: Eclipse’s Workspace Launcher.
FIGURE 2-10: Eclipse’s Workspace Launcher.

In the tree on the left side of the Preferences dialog, expand the Java branch

Within the Java branch, select the Installed JREs

  • Look at the list of Java versions (Installed JREs) in the main body of the Preferences dialog
  • If your preferred version of Java appears on the Installed JREs list, put a check mark in that version’s check box
  • If your preferred version of Java doesn’t appear in the Installed JREs list, click the Add button
  • In the JRE Type dialog, double-click Standard VM
  • Fill in the dialog’s JRE Home field
    • jdk icon or some other item whose extension is
  • Look at the JRE Definition dialog’s JRE Name field; if Eclipse hasn’t filled in a name automatically, type a name
  • Dismiss the JRE Definition dialog by clicking Finish
  • Put a check mark in the check box next to your newly added version of Java
  • In the Compiler Compliance Level drop-down list, select a number that matches your preferred Java version
  • Whew! Click the Preferences dialog’s OK button to return to the Eclipse workbench
  • Follow the steps in this chapter’s earlier section “ Getting This Book’s Sample Programs .”
  • In the Import dialog’s tree, expand the General branch
  • In the Import Projects dialog, choose either the Select Root Directory radio button or the Select Archive File radio
  • Click the Browse button to find the

In the main section of the Preferences dialog, you'll see a compiler compliance level drop-down list. In the Compiler Compliance Level drop-down list, select a number that matches your preferred Java version. number that matches your preferred Java version. First, make sure you've followed the advice I give in the previous sidebar titled “The Annoying File Names.

Then look in the folder with the file you downloaded from this book's website.

FIGURE 2-13: Eclipse’s Preferences dialog.
FIGURE 2-13: Eclipse’s Preferences dialog.

Click the Select All button

To make sure you can tell the difference between a folder and a .zip file, check this chapter's "Annoying Filename". For a full breakdown of .zip files and other archive files, see the sidebar titled "Compressed Archive Files.

Click the Finish button

If you are reading this section, you have probably finished installing Java and Eclipse on your computer.

FIGURE 2-16: Starting to import this book’s code.
FIGURE 2-16: Starting to import this book’s code.

Running Programs

  • Make sure that you’ve followed the instructions in Chapter 2
  • Launch Eclipse
  • In the Workspace Launcher dialog box, click OK
  • In the Package Explorer, click the 03-0-Mortgage  branch
  • The 03-0-Mortgage project is the only project whose name isn’t two digits, a dash, and then two more digits
    • Choose Run ⇒ Run As ⇒ Java Application from the main menu, as shown in Figure 3-4
    • Click anywhere inside Eclipse’s Console view and then type a number, like 100000.00, and press Enter
    • In response to the interest rate question, type a number, like 5.25, and press Enter
    • Type a number, like 30, and press Enter
    • From Eclipse’s menu bar, choose File ⇒ New ⇒ Java Project
    • In the New Java Project dialog box, type a name for your project and then click Finish
    • Select your newly created project in the Package Explorer
    • In Eclipse’s main menu, choose File ⇒ New ⇒ Class
    • In the New Java Class dialog box’s Name field, type the name of your new class
    • Replace an existing line of code in your new Java program
    • Make any changes or corrections to the code in Eclipse’s editor
    • From Eclipse’s main menu, choose Run ⇒ Run As ⇒ Java Application

After you press Enter, the Java program displays another message ( How many years ... ? ) in the console view. When you start Eclipse, type a new folder name in the Workspace field of Eclipse's Workspace Launcher dialog box. MyFirstProject in the Package Explorer in Windows (or Control-click MyFirstProject in the Package Explorer on a Mac).

In the New Java Class dialog box, enter the name of your new class in the Name field.

FIGURE 3-1: A run of this chapter’s text-based mortgage program.
FIGURE 3-1: A run of this chapter’s text-based mortgage program.

SEE FORMATTING IN MY JAVA PROGRAM?

With a Java program editor, things like bold and coloring are not marked inside the Java program file. Instead, the editor displays each word in a way that makes the Java program easy to read.

WHAT CAN POSSIBLY GO WRONG?

You can switch between perspectives by choosing Window ⇒ Open Perspective in Eclipse's main menu bar. Switch back to the Java perspective by choosing Window ⇒ Perspective ⇒ Open Perspective ⇒ Java from the Eclipse main menu. In Eclipse's editor, change the lowercase c in the word class to an uppercase C.

But when you try to run the program, you see red text in Eclipse Console view.

FIGURE 3-15: The workbench is divided into areas.
FIGURE 3-15: The workbench is divided into areas.

Writing Your Own Java Programs

Exploring the Parts of a Program

Follow the instructions in Chapter 2 for installing Eclipse

Then follow the instructions in the first half of Chapter 3 . Those instructions tell you how to run the project named 03-01

Comparing Java with English, I can write: "Names of things are not the same as words in the dictionary." Sure, you can argue that some dictionaries list proper names and that some people have first names like Hope, Prudence, and Spike, but please don't. For now, don't worry about the other words in the method header—the words public, static, void, string, and args. The method call for the System.out.println method is the only statement in the body of the main method.

Statements in the API that tell the computer what it means to make a call to System.out.println are very similar to the Java code in Listing 4-1.

FIGURE 4-2: The things you find in a simple sentence.
FIGURE 4-2: The things you find in a simple sentence.

Composing a Program

  • At first, the computer does nothing
  • You click inside Eclipse’s Console view
  • From Eclipse’s menu bar, choose File ⇒   New ⇒   Java Project
  • In the dialog box’s Project Name field, type MyNewProject
  • Click Finish
  • Click Finish
  • Type the program of Listing 5-1 in the EchoLine.java editor
  • Make any changes or corrections to the code in the editor

The text in the image is a mixture of my typing and the computer's responses. Clicking Finish returns you to the Eclipse desktop, with MyNewProject in the Package Explorer. In the Package Explorer, select MyNewProject, and then, on the Eclipse main menu, select File ⇒ New ⇒ Class.

In the Name field of the New Java Class dialog box, enter the name of your new class.

Explorer

On Eclipse’s main menu, choose Run ⇒   Run As ⇒   Java Application

Click inside Eclipse’s Console view

Type a line of text and then press Enter

When the computer runs your program, the computer substitutes what you type on the keyboard for the text keyboard.nextLine(). When you run the program, the computer sees your call to NextLine and stops in its tracks. In Listing 5-1, the words keyboard.nextLine() get a full line of text from the computer's keyboard. the program in Listing 5-1 repeats the entire Testing 1 2 3 line of text.

For example, if you type 1 2 3, you might want the computer to get the number 1. Maybe the number 1 represents one customer or something like that.).

A QUICK LOOK AT THE SCANNER

Case sensitive means, among other things, that in a Java program the letter P is not the same as the letter p. In plain English, this means: “The Java compiler cannot interpret the word Println.” (The message ends by saying, "Don't type the word Println, you Dummy!" Anyway, if the computer says you're one of us Dummies, you should take that as a compliment.) Now, there are plenty of reasons why the compiler can. If you right-click the highlight in the left margin (or Control-click on a Mac) and choose Quick Fix from the resulting context menu, Eclipse will display the suggested fixes.

I don't have to explain the message, and you don't have to puzzle over the message's meaning.

WHY CAN’T THE COMPUTER FIX IT?

So this is the error message - the computer says This method requires a body instead of a semicolon. You come to a fork in the road and say to yourself, "The directions didn't say anything about a fork. Which way should I go?" You turn right, but a minute later you are forced onto a highway.

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 requires a starting point called main, with a small m.

FIGURE 5-8: An unwanted semicolon messes things up.
FIGURE 5-8: An unwanted semicolon messes things up.

Using the Building Blocks

Variables, Values, and Types

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. Modify the code in Listing 6-1 to display three values: the original price of the flash drive, the cost of shipping and handling, and the total cost. The computer doesn't really rewrite the code in Listing 6-2.. 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 stored in amount.

FIGURE 6-3: A variable, its value, and its type.
FIGURE 6-3: A variable, its value, and its type.

WHO DOES WHAT, AND HOW?

If the user and the programmer are the same person, and the program is fairly simple, knowing what to type is not a big problem. When you start writing programs, you can easily confuse the roles of the incentive and the user's input. If you call print or println but you don't call a keyboard.next Something method, the computer doesn't wait for the user to type something.

The code in Listing 6-1 has only one variable (as if variables are missing).

FIGURE 6-8: A failed attempt to compile  BadSnitSoftCode  .
FIGURE 6-8: A failed attempt to compile BadSnitSoftCode .

Gambar

FIGURE 1-3: What the computer gleans from a bytecode file.
FIGURE 1-4: How a computer runs a Java program.
FIGURE 2-1: Getting the Java JDK.
FIGURE 2-3: The Java Preferences application.
+7

Referensi

Dokumen terkait