Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Writing Your First Program in Java

java



+ Font mai mare | - Font mai mic



Writing Your First Program

As you learned during Hour 1, 'Becoming a Programmer,' a computer program is a set of instructions that tell a computer what to do. These instructions are prepared in the same way instructions could be given to a person: You type them into a word processor. However, that's where the similarity ends. Instructions given to a computer must be written using a programming language. Dozens of computer programming languages have been created; you might have heard of some of them, such as BASIC or Pascal.



During this hour, you will create your first Java program by entering it using any word processor you like. When that's done, you will save the program, compile it, and test it out. The following topics will be covered during this hour:

Entering a program into a word processor

Naming a Java program with the class statement

Organizing a program with bracket marks

Storing information in a variable

Changing the value of a variable

Displaying the information stored in a variable

Saving a program

Compiling a program

Running a program

Fixing errors

Modifying a program

What You Need to Write Programs

As explained in Hour 1, you should have installed the current version of the Java Developer's Kit on your system. The kit contains tools that enable you to compile and test Java programs. You also need a word processor to write programs.

With most programming languages, computer programs are written by entering text into a word processor (also called a text editor). Some programming languages, such as Visual C++ from Microsoft, come with their own word processor. SunSoft Java WorkShop, an advanced programming tool from Java's developers, also comes with its own editor.

Java programs are simple text files without any special features such as centered text, boldface text, or other enhancements. They can be written with any word processing program that can create text files. Microsoft Windows systems have several word processors you can use, including Notepad, WordPad, and the DOS program edit. Apple Macintosh users can create programs with Simple Text or other editors such as BBEdit Lite. Any of these programs will work fine.

Some word-processing programs are available on the CD-ROM that accompanies this book, including BBEdit Lite.

You also can use more sophisticated word processors, such as Microsoft Word, if you remember to save the programs as text. This option has different names depending on the program you are using. In Word, the file should be saved as a file of type Text Only. Other programs call these files DOS text, ASCII text, or something similar.

Caution: If you're in doubt as to whether a word processor can save files as text files, you can always use one of the simple programs that comes with your operating system. Windows users can use Notepad to create Java programs because text files created with Notepad are always saved as text-only files.

After you have decided which word processor you will use to write Java programs, go ahead and load it so you can start writing a program.

Windows 95 users must take one extra step before saving any Java-related files to disk: The .java file extension must be associated with the selected word processor. To do this, you need to create a new .java file and load it into the word processor you'll be using during this book.

To create the file, open up any file folder on your system and press the right-click button on your mouse. A pop-up menu will appear that will enable you to choose the New | Text Document option. Choose this option and a file named New Text Document.txt will appear. Change the name of this file to Anything.java and confirm that you really want to choose the new name.

If you have never written Java programs on your computer, the .java file extension should not be associated with any programs yet. Double-click the Anything.java file with the left mouse button and a dialog box will appear, enabling you to choose a program for opening the .java file. Choose your preferred word processor, first making sure to click the option Always use this program to open this file.

Creating the BigDebt Program

One of the things that computers are best at is math, a task that most humans are happy to pass off to someone else (or something else, in this case). For your first Java program, you will use the computer to determine a depressing fact about the financial condition of the United States. Your program will be called BigDebt. The program figures out how much the national debt increases in an average minute. In order to determine this amount, the computer will be told how much the debt increases in an average day.

The national debt is the amount the United States government has borrowed to compensate for budget deficits over the years. It was approaching $5.25 trillion at last count, which equals $19,700 in indebtedness for each resident of the United States. The following table shows the debt since 1960:

1960:$290.2 billion1965:$320.9 billion1970:$389.2 billion1975:$576.6 billion1980:$930.2 billion1985:$1.946 trillion 1990:$3.365 trillion1995:$4.989 trillionEd Hall maintains a Web page with the current national debt, updated continuously. It's available at the following location:

<https://www.brillig.com/debt_clock/>

Beginning the Program

Using your word processor, begin your Java programming career by entering each line from Listing 2.1. Don't enter the line number and colon at the beginning of each line--these are used in this book so that specific line numbers can be referred to.

Listing 2.1. The BigDebt program.

1: class BigDebt


Make sure to capitalize everything exactly as shown, and use your Tab key or space bar to insert the blank spaces in front of some lines. When you're done, save the file with the file name
BigDebt.java. Figure 2.1 shows the full text of Listing 2.1 entered using the Zeus for Windows word processor and saved as BigDebt.java

You have created the bare-bones form of a Java program. You will create several programs that start off exactly like this one, except for the word BigDebt on Line 1. This word represents the name of your program and changes with each program that you write. Line 3 also should make sense--it's a sentence in actual English. The rest is completely new, however, and each part is introduced in the following sections.

Figure 2.1. <../art/02/02tja01.jpg> Entering BigDebt.java using the Zeus for Windows word- processing program.

The class Statement

The first line of the program is the following:

class BigDebt . These brackets are a way to group parts of your program (in the same way that parentheses are used in this sentence to group words). Everything between the opening bracket, , is part of the same group.

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

Blocks can be located inside other blocks (just as parentheses are used here (and a second set is used here)). The BigDebt.java program has brackets on Line 2 and Line 4 that establish another block. This block begins with the main statement. Everything inside the main statement block is a command for the computer to handle when the program is run.

The following statement is the only thing located inside the block:

// My first Java program goes here

This line is a placeholder. The at the beginning of the line tells the computer to ignore this line--it is put in the program solely for the benefit of humans who are looking at the program's text. Lines that serve this purpose are called comments.

Right now, you have written a complete Java program. It can be compiled, but if you run it, nothing will happen. The reason for this is that you have not told the computer to do any-thing yet. The main statement block contains only a line of comments, which is ignored. If the BigDebt.java program is going to provide sobering details about the United States Treasury, you will have to add some commands inside the opening and closing brackets of the main statement block.

Storing Information in the debt Variable

The national debt is increasing at a present rate of $59 million per day. To put this number into perspective, overpaid sports athletes could donate their salaries to the United States Treasury and barely make a dent in it. Chicago White Sox slugger Albert Belle's five-year, $50 million deal stops the debt from increasing for about 20 hours.

Aside from the publishers of computer books, most of us don't make the same kind of money as pro athletes. If we want to slow down the growing debt ourselves, a place to start is by breaking it down into minutes. Your Java program will figure this out for you.

The first step is to tell the computer what you were just told: The national debt goes up $59 million per day. Load the BigDebt.java file into your word processor if it's not still loaded, and replace Line 3 with the following:

int debt = 59000000;

This statement tells the computer to store the value 59,000,000 into a variable called debt. Variables are special storage places where a computer program can store information. The value of variables can be changed.

Variables can be used to hold several different types of information, such as integers, floating-point numbers, lines of text, and characters of text. In a Java program, you must tell the computer what type of information a variable will hold. In this program, debt is an integer. Putting int in the statement int debt = 59000000; sets up the variable to hold integer values.

The int variable type can store values from -2.1 billion to 2.1 billion in Java programs. There are other variable types for different types of numbers and other types of information.

When you entered this statement into the computer program, a semi-colon should have been included at the end of the line. Semi-colons are used at the end of each command in your Java programs. They're like periods at the end of a sentence; the computer uses them to determine when one command ends and the next command begins.

Changing the Information Stored in debt

As it stands, the program you have written does one thing: It uses the debt variable to hold the value 59,000,000--a day's worth of growing debt. However, you want to determine the amount of debt per minute, not per day. To determine this amount, you need to tell the computer to change the value that has been stored in the debt variable. There are 1,440 minutes in each day, so tell the computer to divide the value in debt by 1,440.

Insert a blank line after the int debt = 59000000; statement. In the blank line, enter the following:

debt = debt / 1440;

If you haven't been able to suppress all memories of new math, this statement probably looks like an algebra problem to you. It gives the computer the following assignment: 'Set the debt variable equal to its current value divided by 1,440.'

You now have a program that does what you wanted it to do. It determines the amount the national debt grows in an average minute. However, if you ran the program at this point, it wouldn't display anything. The two commands you have given the computer in the BigDebt program occur behind the scenes. To show the computer's result, you have to display the contents of the debt variable.

Displaying the Contents of debt

Insert another blank line in the BigDebt program after the debt = debt / 1440; statement. Use that space to enter the following statement:

System.out.println('A minute's worth of debt is $' + debt);

This statement tells the computer to display the text A minute's worth of debt is $ followed by the value stored in the debt variable. The System.out.println command means 'display a line on the system output device.' In this case, the system output device is your computer monitor. Everything within the parentheses is displayed.

Saving the Finished Product

Your program should now resemble Listing 2.2. Make any corrections that are needed and save the file as BigDebt.java. Keep in mind that all Java programs are created as text files and are saved with the .java file extension.

Listing 2.2. The finished version of the BigDebt program.

1: class BigDebt


When the computer runs this program, it will run each of the statements in the
main statement block on lines 3 through 5. Listing 2.3 shows what the program would look like if it were written in the English language instead of Java.

Listing 2.3. A line-by-line breakdown of the BigDebt program.

1: The BigDebt program begins here:

The main part of the program begins here:

Store the value 59000000 in an integer variable called debt

Set debt equal to its current value divided by 1440

Display 'A minute's worth of debt is $' and the new value of debt

The main part of the program ends here.

7: The BigDebt program ends here.

Compiling the Program into a Class File

Before you can try out the program, it must be compiled. The term compile might be unfamiliar to you now, but you will become quite familiar with it in the coming hours. When you compile a program, you take the instructions you have given the computer and convert them into a form the computer can better understand. You also make the program run as efficiently as possible. Java programs must be compiled before you can run them. With the Java Developer's Kit, programs are compiled with the javac tool.

To compile the BigDebt program, go to the directory on your system where the BigDebt.java file is located, and type the following command:

javac BigDebt.java

When the program compiles successfully, a new file called BigDebt.class is created in the same directory as BigDebt.java. (If you have any error messages, refer to the following section, 'Fixing Errors.') The .class extension was chosen because all Java programs also are called classes. A Java program can be made up of several classes that work together, but in a simple program such as BigDebt only one class is needed.

Do you have a relative, spouse, or other loved one who only says something when things go wrong? (Me neither.) The javac tool only speaks up when there's an error to complain about. If you compile a program successfully without any errors, nothing happens in response.

Fixing Errors

If errors exist in your program when you compile it, the javac tool displays a message explaining each error and the lines they occurred on. Figure 2.2 shows an attempt to compile a program that has errors, and the error messages that are displayed as a result.

Error messages displayed by the javac tool include the following information:

The name of the Java program

The number of the line where the error was found

The type of error

The line where the error was found

Figure 2.2. <../art/02/02tja02.jpg> Compiling a version of the BigDebt program that has errors.

As you learned during the past hour, errors in programs are called bugs. Finding those errors and squashing them is called debugging. The following is an example of an error message from Figure 2.2:

BigDebt.java:4: Invalid type expression.

debt = debt / 1440

In this example, the that follows the file name BigDebt.java indicates that the error is on Line 4. The actual error message, Invalid type expression in this case, can often be con-fusing to new programmers. In some cases, the message can be confusing to any programmer. When the error message doesn't make sense to you, take a look at the line where the error occurred.

For instance, can you determine what's wrong with the following statement?

debt = debt / 1440

The problem is that there's no semi-colon at the end of the statement, which is required in Java programs.

If you get error messages when compiling the BigDebt program, double-check that your program matches Listing 2.2, and correct any differences you find. Make sure that everything is capitalized correctly, and all punctuation (such as , and ) is included. Often, a close look at the statement included with the error message is enough to reveal the error, or errors, that need to be fixed.

Running the Program

The Java Developer's Kit provides a Java interpreter so that you can try the program you have created. The interpreter makes the computer follow the instructions you gave it when you wrote the program. To see whether the BigDebt program does what you want, go to the directory that contains the BigDebt.class file, and type the following:

java BigDebt

When the program runs, it should state the following:

A minute's worth of debt is $40972

The computer has provided the answer you wanted! With this information, you now know that if you want to donate your salary to slow one minute's growth of the national debt, you need to make more than $40 grand per year. You also have to avoid paying any taxes.

Caution: Neither the author nor Sams.net Publishing makes any guarantees express or implied that the Internal Revenue Service will accept the excuse that you spent all your money on the national debt.

Workshop: Modifying the Program

The BigDebt program calculated the amount the national debt increases in a minute. If you'd like to make a dent in the debt but can't spare $40,000, you might want to see how much a second's worth of debt would cost you.

Load the file BigDebt.java into your word processor again. You need to change the following statement:

debt = debt / 1440;

This line divided the value in the debt variable by 1,440 because there are 1,440 minutes in a day. Change the line in the BigDebt program so that it divides the debt variable by 86,400, the amount of seconds in a day.

Caution: When you change the line of code, don't include a comma in the number (as in ).If you do, you will get an error message when you compile the program. Commas may make it easier for people to read the numbers in your code, but the compiler doesn't appreciate the gesture.

You also need to change the following line:

System.out.println('A minute's worth of debt is $' + debt);

Now that you're calculating a second's worth of debt, you need to replace the word minute with second. Make the change and save the file BigDebt.java. Your version of BigDebt.java should match Listing 2.4.

Listing 2.4. The modified version of the BigDebt program.

1: class BigDebt


Compile the file with the same command that you used previously:

javac BigDebt.java

When you run the program, you should get the following output:

A second's worth of debt is $682

Summary

During this hour, you got your first chance to create a Java program. You learned that to create a Java program you need to complete these three basic steps:

Write the program with a word processor.

2.
Compile the program.

3.
Tell the interpreter to run the program.

Along the way, you were introduced to some basic computer programming concepts such as compilers, interpreters, blocks, statements, and variables. These things will become more clear to you in successive hours. As long as you got the program to work during this hour, you're ready to proceed.

Q&A

Q Is SunSoft Java WorkShop another programming language like Java, or is it something else?

A
Java WorkShop is a way to write Java programs in a graphical, point-and-click environment. It was produced by a division of Sun Microsystems, the developer of Java, as an improvement upon the Java Developer's Kit. Other products in the market offer similar features, such as Symantec Caf, Microsoft J++, and RogueWave JFactory. For more information on these products, see Appendix B, 'Java Programming Tools.'

Q I have several word processing programs on my system. Which should I use to write Java programs?

A
Any of them will suffice, as long as it can save files as text without any special formatting. A word processor that shows the line number your cursor is located on is especially useful. (Microsoft Word, for example, shows the line number at the bottom edge of the window along with the column number.) Because the
javac compiler lists line numbers with its error messages, the line-numbering feature helps you debug a program more quickly.

Q How important is it to put the right number of blank spaces on a line in a Java program?

A
Spacing is strictly for the benefit of people looking at a computer program. You could have written the
BigDebt program without using blank spaces or the Tab key to indent lines, and it would compile successfully. Although the number of spaces in front of the lines isn't important, you should use spacing in your Java programs. Spacing indicates how a program is organized and which programming block a statement belongs to. When you start writing more sophisticated programs, you'll find it much more difficult to do without spacing.

Q A Java program has been described as a class, and it also has been described as a group of classes. Which is it?

A
Both. The simple Java programs that you create during the next few hours will create a single file with the extension
.class. You can run these programs with the java interpreter. Java programs also can consist of a set of classes that work together. In fact, even simple programs like BigDebt use other Java classes behind the scenes. This topic will be fully explored during Hour 10, 'Creating Your First Object.'

Q If semi-colons are needed at the end of each statement, why does the comment line // My first Java program goes here not end with a semi-colon?

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

debt = debt / 86400; // divide debt by the number of seconds

In this example, the compiler will handle the statement debt = debt / 86400; and ignore the comments afterward.

Q What is a character?

A
A character is a single letter, number, punctuation mark, or other symbol. Examples are T, 5, and %. Characters are stored in variables as text.

Q I get an Invalid argument error message when I use the javac tool to compile the BigDebt program. What can I do to correct this?

A
You are probably leaving off the
.java extension and typing the following command:

javac BigDebt

Make sure that you are in the same directory as the file BigDebt.java, and type the following command to compile the program:

javac BigDebt.java

Q I couldn't find any errors in the line where the compiler noted an error. What can I do?

A
The line number displayed with the error message isn't always the place where an error needs to be fixed in your program. Examine the statements that are directly above the error message to see whether you can spot any typos or other bugs. The error usually is within the same programming block.

Quiz

Test your knowledge of the material covered in this chapter by answering the following questions.

Questions

When you compile a Java program, what are you doing?

(a)
Saving it to disk
(b) Converting it into a form the computer can better understand
(c) Adding it to your program collection

2.
What is a variable?

(a)
Something that wobbles but doesn't fall down.
(b) Text in a program that the compiler ignores.
(c) A place to store information in a program.

3.
What is the process of fixing errors called?

(a)
Defrosting
(b) Debugging
(c) Decomposing

Answers

b. Compiling converts a .java file into a .class file or set of .class files.

2.
c. Variables are one place to store information; later you'll learn about others such as arrays and constants. Weebles wobble but they don't fall down, and comments are text in a program that the compiler ignores.

3.
b. Because errors in a computer program are called bugs, fixing those errors is called debugging. Some programming tools come with a feature called a debugger that helps you fix errors.

Activities

If you'd like to explore the topics covered in this hour a little more fully, try the following activities:

Write a program for megamillionaires: Calculate the amount the national debt increases in a week.

Go back to the BigDebt program and add one or two errors. For example, take a semi-colon off the end of a line, or change the line that reads class BigDebt { into class bigDebt {. Save the program and try to compile it. Compare the error messages you get to the errors you caused.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 711
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved