没有合适的资源?快使用搜索试试~ 我知道了~
首页big java 6ed
资源详情
资源评论
资源推荐

Big Java
Cay Horstmann
6/e
Early Objects
Includes Java 8 coverage
Horstmann_BJ6_JC8_cvs_final_cj.indd 1 4/29/15 1:46 PM

Selected Operators and Their Precedence
(See Appendix B for the complete list.)
[]
Array element access
++ -- !
Increment, decrement, Boolean not
* / %
Multiplication, division, remainder
+ -
Addition, subtraction
< <= > >=
Comparisons
== !=
Equal, not equal
&&
Boolean and
||
Boolean or
=
Assignment
Conditional Statement
if (floor >= 13)
{
actualFloor = floor - 1;
}
else if (floor >= 0)
{
actualFloor = floor;
}
else
{
System.out.println("Floor negative");
}
Condition
Executed when condition is true
Second condition (optional)
Executed when
all conditions are
false (optional)
Class Declaration
public class CashRegister
{
private int itemCount;
private double totalPrice;
public void addItem(double price)
{
itemCount++;
totalPrice = totalPrice + price;
}
. . .
}
Method
Instance variables
do
{
System.out.print("Enter a positive integer: ");
input = in.nextInt();
}
while (input <= 0);
for (double value : values)
{
sum = sum + value;
}
An array or collection
Executed for each element
Loop body executed
at least once
Set to a new element in each iteration
Executed while
condition is true
Condition
Initialization Condition Update
Loop Statements
while (balance < TARGET)
{
year++;
balance = balance * (1 + rate / 100);
}
for (int i = 0; i < 10; i++)
{
System.out.println(i);
}
String Operations
String s = "Hello";
int n = s.length(); // 5
char ch = s.charAt(1); // 'e'
String t = s.substring(1, 4); // "ell"
String u = s.toUpperCase(); // "HELLO"
if (u.equals("HELLO")) ... //
Use
equals
, not
==
for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
Process
ch
}
Mathematical Operations
Math.pow(x, y)
Raising to a power x
y
Math.sqrt(x)
Square root x
Math.log10(x)
Decimal log log
10
(x)
Math.abs(x)
Absolute value |x|
Math.sin(x)
Math.cos(x)
Sine, cosine, tangent of x (x in radians)
Math.tan(x)
Variable and Constant Declarations
int cansPerPack = 6;
final double CAN_VOLUME = 0.335;
Type Name Initial value
Parameter
type and name
Exits method and
returns result.
Return typeModiers
Method Declaration
public static double cubeVolume(double sideLength)
{
double volume = sideLength * sideLength * sideLength;
return volume;
}
Input
Scanner in = new Scanner(System.in);
//
Can also use
new Scanner(new File("input.txt"));
int n = in.nextInt();
double x = in.nextDouble();
String word = in.next();
String line = in.nextLine();
while (in.hasNextDouble())
{
double x = in.nextDouble();
Process
x
}
Linked Lists, Sets, and Iterators
LinkedList<String> names = new LinkedList<>();
names.add("Bob"); //
Adds at end
ListIterator<String> iter = names.listIterator();
iter.add("Ann"); //
Adds before current position
String name = iter.next(); //
Returns
"Ann"
iter.remove(); //
Removes
"Ann"
Set<String> names = new HashSet<>();
names.add("Ann"); //
Adds to set if not present
names.remove("Bob"); //
Removes if present
Iterator<String> iter = names.iterator();
while (iter.hasNext())
{
Process
iter.next()
}
Arrays
int[] numbers = new int[5];
int[] squares = { 0, 1, 4, 9, 16 };
int[][] magicSquare =
{
{ 16, 3, 2, 13},
{ 5, 10, 11, 8},
{ 9, 6, 7, 12},
{ 4, 15, 14, 1}
};
for (int i = 0; i < numbers.length; i++)
{
numbers[i] = i * i;
}
for (int element : numbers)
{
Process element
}
System.out.println(Arrays.toString(numbers));
//
Prints
[0, 1, 4, 9, 16]
Element
Element type type Length
All elements are zero.
Maps
Map<String, Integer> scores = new HashMap<>();
scores.put("Bob", 10);
Integer score = scores.get("Bob");
for (String key : scores.keySet())
{
Process
key
and
scores.get(key)
}
Key type Value type
Returns
null
if key not present
Output
System.out.print("Enter a value: ");
System.out.println("Volume: " + volume);
System.out.printf("%-10s %10d %10.2f", name, qty, price);
try (PrintWriter out = new PrintWriter("output.txt"))
{
Write to
out
}
Left-justied string Integer Floating-point number
Field width Precision
Does not advance to new line.
Use
+
to concatenate values.
The output is closed at the end of
the
try
-with-resources statement.
Use the
print
/
println
/
printf
methods.
Array Lists
ArrayList<String> names = new ArrayList<String>();
names.add("Ann");
names.add("Cindy"); // [Ann, Cindy], names.size()
is now 2
names.add(1, "Bob"); // [Ann, Bob, Cindy]
names.remove(2); // [Ann, Bob]
names.set(1, "Bill"); // [Ann, Bill]
String name = names.get(0); //
Gets
"Ann"
System.out.println(names); //
Prints
[Ann, Bill]
Element type
(optional)
Use wrapper type,
Integer
,
Double
,
etc., for primitive types.
Add elements to the end
Initially empty
bj6_insidecovers_8x10.indd 1 4/30/15 3:48 PM

Big Java
6/e
Early Objects
Cay Horstmann
San Jose State University

VICE PRESIDENT AND EXECUTIVE PUBLISHER Laurie Rosatone
DIRECTOR Don Fowley
EXECUTIVE EDITOR Bryan Gambrel
EDITORIAL PROGRAM ASSISTANT Jessy Moor
MARKETING MANAGER Dan Sayre
SENIOR PRODUCT DESIGNER Jennifer Welter
DESIGN DIRECTOR Harry Nolan
SENIOR DESIGNER Madelyn Lesure
SENIOR PHOTO EDITOR Billy Ray
SENIOR CONTENT EDITOR Karoline Luciano
SENIOR PRODUCTION EDITOR Tim Lindner
PRODUCTION MANAGEMENT SERVICES Cindy Johnson
COVER DESIGN Madelyn Lesure
COVER PHOTOS (tiger) Aprison Photography/Getty Images, Inc.;
(rhino) irawansubingarphotography/Getty
Images, Inc.; (bird) Nengloveyou/Shutterstock;
(monkey) © Ehlers/iStockphoto.
This book was set in 10.5/12 Stempel Garamond LT Std by Publishing Services, and printed and bound by Quad
Graphics/Versailles. The cover was printed by Quad Graphics/Versailles.
This book is printed on acid-free paper. ∞
Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than
200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is built on
a foundation of principles that include responsibility to the communities we serve and where we live and work.
In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental, social, eco-
nomic, and ethical challenges we face in our business. Among the issues we are addressing are carbon impact, paper
specifications and procurement, ethical conduct within our business and among our vendors, and community and
charitable support. For more information, please visit our website: www.wiley.com/go/citizenship.
Copyright © 2015 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be repro-
duced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechani-
cal, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher,
or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Cen-
ter, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the
Web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions
Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201)
748-6008, or online at: www.wiley.com/go/permissions.
Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in
their courses during the next academic year. These copies are licensed and may not be sold or transferred to a
third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc-
tions and a free of charge return shipping label are available at: www.wiley.com/go/returnlabel. Outside of the
United States, please contact your local representative.
ISBN 978-1-119-05628-7
ISBN-BRV 978-1-119-05644-7
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1

PREFACE
iii
This book is an introduction to Java and computer programming that focuses on the
essentials—and on effective learning. The book is designed to serve a wide range of
student interests and abilities and is suitable for a first course in programming for
computer scientists, engineers, and students in other disciplines. No prior program-
ming experience is required, and only a modest amount of high school algebra is
needed.
Here are the key features of this book:
Start objects early, teach object orientation gradually.
In Chapter 2, students learn how to use objects and classes from the standard library.
Chapter 3 shows the mechanics of implementing classes from a given specification.
Students then use simple objects as they master branches, loops, and arrays. Object-
oriented design starts in Chapter 8. This gradual approach allows students to use
objects throughout their study of the core algorithmic topics, without teaching bad
habits that must be un-learned later.
Guidance and worked examples help students succeed.
Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “How To” guides help students with
common programming tasks. Additional Worked Examples are available online.
Problem solving strategies are made explicit.
Practical, step-by-step illustrations of techniques help students devise and evaluate
solutions to programming problems. Introduced where they are most relevant, these
strategies address barriers to success for many students. Strategies included are:
• Algorithm Design (with pseudocode)
•
Tracing Objects
• First Do It By Hand (doing sample
calculations by hand)
• Flowcharts
• Selecting Test Cases
• Hand-Tracing
• Storyboards
• Solve a Simpler Problem First
• Adapting Algorithms
• Discovering Algorithms by
Manipulating Physical Objects
• Patterns for Object Data
• Thinking Recursively
• Estimating the Running Time of
an Algorithm
Practice makes perfect.
Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. This book contains
a substantial number of self-check questions at the end of each section. “Practice It”
pointers suggest exercises to try after each section. And additional practice oppor-
tunities, including automatically-graded programming exercises and skill-oriented
multiple-choice questions, are available online.
剩余1443页未读,继续阅读

















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0