• Tidak ada hasil yang ditemukan

Java™ An Introduction to Problem Solving & Programming

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Membagikan "Java™ An Introduction to Problem Solving & Programming"

Copied!
1056
0
0

Teks penuh

An icon appears in the margin of the book when a VideoNote is available on a topic covered in the text. All imported classes are standard and in the Java Class Library, which is part of Java.

Contact Us

Preface for Students

If You Have Programmed Before

Obtaining a Copy of Java

Support Materials for Students

Learning Aids

Online Practice with Pearson MyLab Programming

VideoNotes

This Text Is Also a Reference Book

You can do this to check details about Java language and details about programming techniques. You can use these functions to review a chapter or to check the details of the Java language.

Acknowledgments

Prasun Dewan—University of North Carolina at Chapel Hill Ricci Heishman—Northern Virginia College Richard A. Rob Kelly—State University of New York at Stony Brook Ryan Shoemaker—Sun Microsystems, Inc.

Acknowledgments for the Global Edition

Contributors

Reviewers

If there is a line between two boxes, the material in the higher box should be covered before the material in the lower box. Minor variations on this scheme are discussed in the "Requirements" section at the beginning of each chapter.

Dependency Chart

Features of This Text

Except in some very standard cases, it is best to include the parentheses even if the intended order of operations is the order indicated by the precedence rules, because the parentheses can make the expression clearer to a person reading the program code. A standard case where it is normal to omit parentheses is a multiplication within an addition.

Specialized Assignment Operators

The method returns true if the receiving object has a greater growth rate than the growth rate of the argument;. So far, we've tested our programs by running them, entering some input, and visually checking the results to see if the output is what we expected.

GRIDLINE SET IN 1ST-PP TO INDICATE SAFE AREA; TO BE REMOVED AFTER 1ST-PP

The number of arguments given in a method call must be exactly the same as the number of formal parameters in the title of the method definition. When a method is called, each parameter is initialized to the value of the corresponding argument in the method call.

Brief Contents

More Swing

Contents

Arrays 513

Programming Example: Processing a Binary Data File 826 10.5 BINARY-FILE I/O WITH OBJECTS AND ARRAYS 831 Binary File I/O with Objects of a Class 831. Creating an ArrayList Example 922 Using Array249 Programming. 928 to-do list.

INTRODUCTION

OBJECTIVES

PREREQUISITES

COMPUTER BASICS

Main memory holds the current program and much of the data that the program manipulates. When you use a program, the contents of the program file are copied from auxiliary memory to main memory.

FIGURE 1.1  Main Memory
FIGURE 1.1 Main Memory

Why just 0s and 1s?

Much of what you think of as "the computer" is actually a program—that is, software. Of course, each type of computer must have its own bytecode interpreter – the JVM – which translates bytecode instructions into machine language instructions for that particular computer, but these interpreters are simple programs compared to a compiler.

Figure 1.2 shows two ways to view the running of a program. To see the  first way, ignore the dashed lines and blue shading that form a box
Figure 1.2 shows two ways to view the running of a program. To see the first way, ignore the dashed lines and blue shading that form a box

SELF-TEST QUESTIONS

A SIP OF JAVA

In Chapter 2, we will explain the details of the Java features used in the program. You run a Java program by giving the command java, followed by the name of the class you think of as the program.

PROGRAMMING BASICS

Polymorphism comes from a Greek word meaning "many forms". The basic idea behind polymorphism is that it allows the same programming instruction to mean different things in different contexts. An error encountered during the execution of a program is called a runtime error.

FIGURE 1.4  An Inheritance Hierarchy
FIGURE 1.4 An Inheritance Hierarchy

GRAPHICS SUPPLEMENT

The x coordinate is the number of pixels from the left edge of the rectangle to the point. The y coordinate is the number of pixels from the top edge of the rectangle to the point. The first two numbers are the x and y coordinates of the upper left corner of the imaginary rectangle enclosing the oval.

The next two numbers give the width and height of the rectangle containing the oval (and thus the width and height of the oval itself). In this example, the lower half of the oval is visible and forms the smile. The last argument specifies how many degrees of the arc of the oval will be made visible.

FIGURE 1.6  Screen Coordinate System
FIGURE 1.6 Screen Coordinate System

CHAPTER SUMMARY

VARIABLES AND EXPRESSIONS

It then uses this value to set the value of the variable on the left side of the assignment operator. You can think of the assignment operator as saying, "Make the value of the variable equal to what follows." You cannot store a value of one type into a variable of another type unless the value is somehow converted to match the type of the variable.

To assign a value of type double to a variable of type int, you must change the type of the value using a type conversion, as explained in the next section. As mentioned earlier, when you assign an integer value to a variable of floating-point type - such as double - the integer is automatically converted to the variable's type. The type of value produced depends on the types of the combined operands.

Figure 2.1 lists all of Java’s primitive types. Four types are for integers,  namely,  byte ,  short ,  int , and  long
Figure 2.1 lists all of Java’s primitive types. Four types are for integers, namely, byte , short , int , and long

SELF-TEST QUESTION

THE CLASS String

Many of the methods for the String class rely on counting positions in the string. That is, the index value must be greater than or equal to zero and less than the length of the string. The Unicode character set contains the full ASCII character set, plus many of the characters used in languages ​​other than English.

You can usually just program as if Java were using the ASCII character set because the ASCII character set is a subset of the Unicode character set. The advantage of the Unicode character set is that it makes it easier to deal with languages ​​other than English. A subset of the Unicode character set, which is synonymous with the ASCII character set, can be found in the appendix of this book.

Figure 2.5 describes some of the methods for the class  String . In the next  chapter, you will learn how to make use of methods such as  equals  and
Figure 2.5 describes some of the methods for the class String . In the next chapter, you will learn how to make use of methods such as equals and

KEYBOARD AND SCREEN I/O

You can use an object of the Scanner class to read input from the keyboard. The nextLine method reads and returns the remainder of the current input line as a string. The next and nextLine methods of the Scanner class read text that begins where the last keyboard read ended.

After this invocation of the useDelimiter method will be the only input delimiter for the input object keyboard2. Also note that you can have two different objects of the Scanner class with different delimiters in the same program. Similarly, there are three blanks in front of the 2 to make a four character field.

FIGURE 2.7  Some Methods in the Class  Scanner
FIGURE 2.7 Some Methods in the Class Scanner

DOCUMENTATION AND STYLE

Comments are notes that you write in your program to help a person understand the program, but are ignored by the compiler. The program in Listing 2.7 has three levels of indentation—as indicated by the vertical lines—which clearly shows the nested structure. In Listing 2.8, we rewrote the program from Listing 2.7 so that it uses the name PI as a defined name for the constant 3.14159.

If the program didn't use a named constant, you would have to change every occurrence of 6.99 to 8.5. While a bit silly, state legislators have been known to pass laws that "change" the value of pi. How to change the program in Listing 2.8 to make it legal.

GRAPHICS SUPPLEMENT

JOptionPane.showInputDialog("Enter number of apples:");. returns—that is, creates—the input that the user typed into the text box. A dialog box—the second one in Listing 2.10—appears and receives an input string from the user. When the user enters a string and clicks the OK button in the window, the method returns the string.

Write a program that reads the amount of a monthly mortgage payment and the amount still owed—the outstanding balance—and then the amount of the payment that goes to interest and the amount that goes to principal (i.e., the amount that goes to the reduction goes) displays the debt). However, there is a "natural" water log tank in the casing (ie the hole) of the well itself. Write a program that allows the user to enter the radius of the well casing in inches (a typical well will have a 3-inch radius) and the depth of the well in feet (assume that water will fill this entire depth , although in practice this will not be true as the static water level will generally be 50 feet or more below the ground surface).

Figure 2.9 lists the correct conversion method for each numeric primitive  type. To convert a value of type  String  to a value of the type given in the first  column of the figure, you use the method given in the second column
Figure 2.9 lists the correct conversion method for each numeric primitive type. To convert a value of type String to a value of the type given in the first column of the figure, you use the method given in the second column

THE if-else STATEMENT

In this chapter, we'll begin to show you how to write programs with more complex control flow. You should be familiar with all the material in Chapter 2 before reading this chapter. This policy can be reflected in the bank's accounting program with the following Java statement, known as an if-else statement:.

The meaning of an if-else statement is actually just the meaning it would have if read as an English sentence. When your program executes the if-else. it first checks the expression in parentheses after the if keyword. In the previous example, if the condition is positive or zero, the following action is performed:.

PROGRAMMING TIP Indentation

Once we know about compound statements, we can say that every. if-else statement is of the form However, a Boolean expression must be enclosed in parentheses when used in an if-else statement. You can use && to form a larger boolean expression from two smaller boolean expressions.

As we noted earlier, the Boolean expression in an if-else statement must be enclosed in parentheses. The value of this expression is the opposite of the value of the Boolean expression: it is true if Boolean_Expression is false and false if Boolean_. For example, if the boolean expression A is true and the boolean expression B is false, A && B evaluates to false.

FIGURE 3.2  The Semantics of the  if-else  Statement
FIGURE 3.2 The Semantics of the if-else Statement

PROGRAMMING TIP Alphabetic Order

If the balance value is greater than or equal to zero, the entire following. In an if-else statement, each else is paired with the closest preceding non-matching if. If the state in the second version is not greater than or equal to zero, no action is taken.

With this trick, you can nest if-else statements to create multi-directional branches that result in any number of possibilities. This statement is actually a regular nested if-else statement, but the way we've indented it reflects the way we think about multi-clause if-else statements. When a multi-branched if-else statement is executed, the computer tests the logical expressions one by one, starting from the top.

Gambar

3  Figure 2.2 shows all the operators we will use in this chapter. More precedence rules  will be given in Chapter 3.
Figure 2.3 shows some examples of how to write arithmetic expressions in  Java and indicates in color some of the parentheses that you can normally omit.
FIGURE 1.1  Main Memory
Figure 1.2 shows two ways to view the running of a program. To see the  first way, ignore the dashed lines and blue shading that form a box
+7

Referensi

Dokumen terkait

Jika a false dan b false maka output adalah