Beruflich Dokumente
Kultur Dokumente
Chapter Goals
Number Types
Every value in Java is either:
a reference to an object
one of the eight primitive types
Primitive Types
Number Literals
A number that appears in your code
If it has a decimal, it is floating point
If not, it is an integer
Number Literals
Overflow
Generally use an int for integers
Overflow occurs when
The result of a computation exceeds the range for the number
type
Example
int n = 1000000;
System .out.println(n * n); // Prints 727379968, w hich is clearly w rong
1012 is larger that the largest int
The result is truncated to fit in an int
No warning is given
Rounding Errors
Constants: f i
n al
Use symbolic names for all values, even those that appear obvious.
A fi
n alvariable is a constant
Once its value has been set, it cannot be changed
Constants: static f i
n al
If constant values are needed in several methods,
Declare them together with the instance variables of a class
Tag them as static and fi
n al
The static reserved word means that the constant belongs to
the class
Give static fi
nalconstants public access to enable other
classes to use them.
10
Constants: static f i
n al
Declaration of constants in the M ath class
public class M ath
{
...
public static fi
naldouble E = 2.7182818284590452354;
public static fi
naldouble PI= 3.14159265358979323846;
}
Using a constant
double circum ference = M ath.PI* diam eter;
11
12
Section_1/CashRegister.java
1/**
2Acashregistertotalsupsalesandcomputeschangedue.
3*/
4publicclassCashRegister
5{
6publicstaticfinaldoubleQUARTER_VALUE=0.25;
7publicstaticfinaldoubleDIME_VALUE=0.1;
8publicstaticfinaldoubleNICKEL_VALUE=0.05;
9publicstaticfinaldoublePENNY_VALUE=0.01;
10
11privatedoublepurchase;
12privatedoublepayment;
13
14/**
15Constructsacashregisterwithnomoneyinit.
16*/
17publicCashRegister()
18{
19purchase=0;
20payment=0;
21}
22
Continued
Copyright 2014 by John Wiley & Sons. All rights
reserved.
13
Section_1/CashRegister.java
23/**
24Recordsthepurchasepriceofanitem.
25@paramamountthepriceofthepurchaseditem
26*/
27publicvoidrecordPurchase(doubleamount)
28{
29purchase=purchase+amount;
30}
31
32/**
33Processesthepaymentreceivedfromthecustomer.
34@paramdollarsthenumberofdollarsinthepayment
35@paramquartersthenumberofquartersinthepayment
36@paramdimesthenumberofdimesinthepayment
37@paramnickelsthenumberofnickelsinthepayment
38@parampenniesthenumberofpenniesinthepayment
39*/
40publicvoidreceivePayment(intdollars,intquarters,
41intdimes,intnickels,intpennies)
42{
43payment=dollars+quarters*QUARTER_VALUE+dimes*DIME_VALUE
44+nickels*NICKEL_VALUE+pennies*PENNY_VALUE;
45}
46
Continued
14
Section_1/CashRegister.java
47/**
48Computesthechangedueandresetsthemachineforthenextcustomer.
49@returnthechangeduetothecustomer
50*/
51publicdoublegiveChange()
52{
53doublechange=paymentpurchase;
54purchase=0;
55payment=0;
56returnchange;
57}
58}
15
Section_1/CashRegisterTester.java
1/**
2ThisclassteststheCashRegisterclass.
3*/
4publicclassCashRegisterTester
5{
6publicstaticvoidmain(String[]args)
7{
8CashRegisterregister=newCashRegister();
9
10register.recordPurchase(0.75);
11register.recordPurchase(1.50);
12register.receivePayment(2,0,5,0,0);
13System.out.print("Change:");
14System.out.println(register.giveChange());
15System.out.println("Expected:0.25");
16
17register.recordPurchase(2.25);
18register.recordPurchase(19.25);
19register.receivePayment(23,2,0,0,0);
20System.out.print("Change:");
21System.out.println(register.giveChange());
22System.out.println("Expected:2.0");
23}
24}
Program Run:
Change: 0.25
Expected: 0.25
Change: 2.0
Expected: 2.0
16
17
18
19
and
public static fi
n aldouble C M _PER_IN C H = 2.54;
20
21
Arithmetic Operators
Four basic operators:
addition: +
subtraction: multiplication: *
division: /
Multiplication and division have a higher precedence than addition and subtraction
a + b /2
22
Arithmetic Operators
Mixing integers and floating-point values in an
arithmetic expression yields a floating-point value
7 + 4.0 is the floating-point value 11.0
23
24
If both numbers are integers, the result is an integer. The remainder is discarded
7 / 4 evaluates to 1
Use % operator to get the remainder with (pronounced modulus, modulo, or mod)
7 % 4 is 3
25
26
27
In Java,
can be represented as
b * M ath.pow (1 + r / 100, n)
Copyright 2014 by John Wiley & Sons. All rights
reserved.
28
Analyzing an Expression
29
Mathematical Methods
30
Use the cast operator (int) to convert a convert floatingpoint value to an integer.
double balance = total+ tax;
int dollars = (int) balance;
31
32
33
Arithmetic Expressions
34
Answer:
double interest = balance * percent / 100;
35
36
37
38
39
40
Reading Input
When a program asks for user input
It should first print a message that tells the user which input is
expected
System .out.print("Please enter the num ber of bottles: "); // D isplay prom pt
41
42
43
Reading Input
A supermarket scanner reads bar
codes. The Java Scanner reads
numbers and text.
44
45
Formatted Output
Use the printf method to specify how values should be
formatted.
printf lets you print this
Price per liter: 1.22
Instead of this
Price per liter: 1.215962441314554
46
Formatted Output
You can also specify a field width:
System .out.printf("% 10.2f", price);
This command
System .out.printf("Price per liter:% 10.2f", price);
Prints
Price per liter: 1.22
47
Formatted Output
You use the printf method to
line up your output in neat
columns.
48
Formatted Output
49
Formatted Output
You can print multiple values with a single call to the
printf method.
Example
System .out.printf("Q uantity: % d Total: % 10.2f",
quantity, total);
Output explained:
50
section_3/Volume.java
1importjava.util.Scanner;
2
3/**
4Thisprogramprintsthepriceperliterforasixpackofcansand
5atwoliterbottle.
6*/
7publicclassVolume
8{
9publicstaticvoidmain(String[]args)
10{
11//Readpriceperpack
12
13Scannerin=newScanner(System.in);
14
15System.out.print("Pleaseenterthepriceforasixpack:");
16doublepackPrice=in.nextDouble();
17
18//Readpriceperbottle
19
20System.out.print("Pleaseenterthepriceforatwoliterbottle:");
21doublebottlePrice=in.nextDouble();
22
Continued
Copyright 2014 by John Wiley & Sons. All rights
reserved.
51
section_3/Volume.java
23finaldoubleCANS_PER_PACK=6;
24finaldoubleCAN_VOLUME=0.355;//12oz.=0.355l
25finaldoubleBOTTLE_VOLUME=2;
26
27//Computeandprintpriceperliter
28
29doublepackPricePerLiter=packPrice/(CANS_PER_PACK*CAN_VOLUME);
30doublebottlePricePerLiter=bottlePrice/BOTTLE_VOLUME;
31
32System.out.printf("Packpriceperliter:%8.2f",packPricePerLiter);
33System.out.println();
34
35System.out.printf("Bottlepriceperliter:%8.2f",bottlePricePerLiter);
36System.out.println();
37}
38}
Program Run
Please enter the price for a six-pack: 2.95
Please enter the price for a tw o-liter bottle: 2.85
Pack price per liter: 1.38
Bottle price per liter: 1.43
Copyright 2014 by John Wiley & Sons. All rights
reserved.
52
53
54
55
56
Answer:
The totalvolum e is 10
57
58
59
60
61
62
Be
63
64
Continued
Copyright 2014 by John Wiley & Sons. All rights
reserved.
65
In the first three entries of the table, the color is simply the sum of the
remainders. In the fourth entry, the sum would be 2, but we want a
zero. We can achieve that by taking another remainder operation:
66
67
68
69
S trin g Type
A string is a sequence of characters.
You can declare variables that hold strings
String nam e = "H arry";
70
S trin g Type
String length is the number of characters in the string
The length of "H arry" is 5
71
Concatenation
Concatenating strings means to put them together
to form a longer string
Use the + operator
Example:
String fN am e = "H arry;
String lN am e = "M organ;
String nam e = fN am e + lN am e;
Result:
"H arryM organ"
Results in
"H arry M organ"
Copyright 2014 by John Wiley & Sons. All rights
reserved.
72
Concatenation
If one of the arguments of the + operator is a string
The other is forced to become to a string:
Both strings are then concatenated
Example
String jobTitle = "Agent;
int em ployeeId = 7;
String bond = jobTitle + em ployeeId;
Result
"Agent7"
73
74
String Input
Use the next method of the Scanner class to read a
string containing a single word.
System .out.print("Please enter your nam e: ");
String nam e = in.next();
75
Escape Sequences
To include a quotation mark in a literal string, precede it
with a backslash ( \ )
"H e said \"H ello\""
76
77
78
Substrings
Use the substring method to extract a part of a string.
The method call str.substring(start, pastEnd)
returns a string that is made up of the characters in the string
str,
starting at position start, and
containing all characters up to, but not including, the position
pastEnd.
Example:
String greeting = "H ello, W orld!;
String sub = greeting.substring(0, 5); // sub is "H ello
79
Substrings
To extract "W orld"
String sub2 = greeting.substring(7, 12);
80
Substrings
If you omit the end position when calling the substring
method, then all characters from the starting position to
the end of the string are copied.
Example
String tail= greeting.substring(7); // Copies allcharacters from position 7 on
Result
Sets tailto the string "W orld!".
81
Substrings
82
section_5/Initials.java
1importjava.util.Scanner;
2
3/**
4Thisprogramprintsapairofinitials.
5*/
6publicclassInitials
7{
8publicstaticvoidmain(String[]args)
9{
10Scannerin=newScanner(System.in);
11
12//Getthenamesofthecouple
13
14System.out.print("Enteryourfirstname:");
15Stringfirst=in.next();
16System.out.print("Enteryoursignificantother'sfirstname:");
17Stringsecond=in.next();
18
19//Computeanddisplaytheinscription
20
21Stringinitials=first.substring(0,1)
22+"&"+second.substring(0,1);
23System.out.println(initials);
24}
Continued
25}
Copyright 2014 by John Wiley & Sons. All rights
reserved.
83
section_5/Initials.java
Program Run
Enter your fi
rst nam e: Rodolfo
Enter your signifi
cant other's fi
rst nam e: Sally
R& S
84
String Operations
85
86
or
str.substring(8)
87
88
Answer:
Hy
89
90
91
92
Chinese Script
93