Beruflich Dokumente
Kultur Dokumente
What is x?
int x = 1729 / 100;
Answer: 17
Integer Division
The volume of a sphere is given by
Answer: 27
Manipulating Places
In general, what is x?
int x = (n / 10) % 10?
Answer:
Dividing by ten always trims off the right-most digit,
so if n was 1234 the n/10 is 123
Mod by ten always returns the right-most digit, so
123%10 is 3.
(n/10)%10 always returns the hundred-place digit
Reading Input
Formatted Output
printf lets you print this
Price per liter: 1.22
Instead of this
Price per liter: 1.215962441314554
Here is how:
double price = 1.215962441314554;
System .out.printf("% .2f", price);
Formatted Output
10
This command
System .out.printf("Price per liter:% 10.2f", price);
Prints
Price per liter:
1.22
Formatted Output
You use the printf to line up output in neat columns.
double
double
System
System
perCup = 1.22;
perG allon = 17.29;
.out.printf(Per cup: % 10.2f", perCup );
.out.printf(Per gallon:% 10.2f", perG allon );
Per cup:
Per gallon:
1.22
17.29
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("Pleaseenterpricefortwoliterbottle:");
21doublebottlePrice=in.nextDouble();
22
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 price for tw o-liter bottle: 2.85
Pack price per liter: 1.38
Bottle price per liter: 1.43
Question
Write statements to prompt for and read the
users age using a Scanner variable named in.
Answer:
System .out.print("H ow old are you? ");
int age = in.nextInt();
Question
What is wrong with the following statement
sequence?
System .out.print("Please enter the unit price: ");
double unitPrice = in.nextD ouble();
int quantity = in.nextInt();
Question
What is problematic about the following
statement sequence?
System .out.print("Please enter the unit price: ");
double unitPrice = in.nextInt();
Answer:
The second statement calls nextInt, not nextD ouble.
If the user were to enter a price such as 1.95, the
program would be terminated with an input
mismatch exception.
Question
What is problematic about the following
statement sequence?
System .out.print("Please enter the num ber of cans");
int cans = in.nextInt();
Question
How many spaces will be between is and 10
int volum e = 10;
System .out.printf("The volum e is % 5d", volum e);
The totalvolum e is 10
Answer:
There are four spaces between is and 10.
One space originates from the format string and
three spaces are added before 10 to achieve a field
width of 5.
Algorithms
Problem: A row of black and white tiles needs to
be placed along a wall. First and last are black.
Compute the number of tiles needed and the gap
at each end, given the space available and the
width of each tile.
Algorithms
Constraint: First and last are black.
Output: the number of tiles needed and the gap
at each end.
Input: space to fill and the width of each tile.
Algorithms
Carry out the computations by hand first
Pick concrete values for a typical situation to use
in a hand calculation.
Algorithms
100 inches
5 inches
Algorithms
The first tile takes up 5
inches, leaving 95 inches to
be
covered by pairs.
Tiles span 19 5 = 95
inches
2.5 inches
Algorithms
Devise an algorithm with arbitrary values for the
total width and tile width.
The pseudocode
number of pairs =
integer part of (total width - tile width) / (2 x tile width)
number of tiles =
1 + 2 x number of pairs
gap at each end =
(total width - number of tiles x tile width) / 2
Question
Translate the pseudocode for computing the
number of tiles and the gap width into Java.
Input: totalW idth and tileW idth
Answer:
int pairs = (totalW idth - tileW idth) / (2 * tileW idth);
int tiles = 1 + 2 * pairs;
double gap = (totalW idth - tiles * tileW idth) / 2.0;
Question
Suppose the architect specifies a pattern with
black, gray, and white tiles, like this:
Question
Answer: Now there are groups of four tiles
(gray/ white/gray/black) following the initial
black tile. Therefore, the algorithm is now
number of groups =
integer part of (total width - tile width) /(4 x tile width)
number of tiles =
1 + 4 x number of groups
Question
number of groups =
integer part of (total width - tile width) /(4 x tile width)
number of tiles =
1 + 4 x number of groups
int groups = (totalW idth - tileW idth) / (4 * tileW idth);
int tiles = 1 + 4 * groups ;
double gap = (totalW idth - tiles * tileW idth) / 2.0;
String Recap
String nam e = "H arry";
nam e is a string variable that points to
a string literal "H arry
String literals are character sequences enclosed
in quotes
String Type
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"
Concatenation
Example
String jobTitle = "Agent;
int em ployeeId = 7;
String bond = jobTitle + em ployeeId;
Result
"Agent7"
Concatenation Recap
Useful to reduce the number of System .out.print
instructions
System .out.print("The totalis ");
System .out.println(total);
versus
System .out.println("The totalis " + total);
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();
Escape Sequences
To include a quotation mark in a literal string,
precede it with a backslash ( \ )
"H e said \"H ello\"
Indicates that the quotation mark that follows
should be a part of the string and not mark the
end of the string
Called an escape sequence
Escape Sequences
To include a backslash in a string, use the escape
sequence \\
"C:\\Tem p\\Secret.txt
A newline character is denoted with the escape
sequence \n
Substrings
Use the substring method to extract a part of a
string.
The method call
str.substring(start, pastEnd)
Example:
String greeting = "H ello, W orld!;
String sub = greeting.substring(0, 5); // sub is "H ello
Substrings
To extract "W orld
String sub2 = greeting.substring(7, 12);
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
o Sets tailto the string "W orld!".
1importjava.util.Scanner;
2
3/**
4Thisprogramprintsapairofinitials.
5*/
6publicclassInitials
7{
8publicstaticvoidmain(String[]args)
9{
10Scannerin=newScanner(System.in);
14System.out.print("Enteryourfirstname:");
15Stringfirst=in.next();
16System.out.print("Enteryourlastname:");
17Stringsecond=in.next();
21Stringinitials=first.substring(0,1)
22+"&"+second.substring(0,1);
23System.out.println(initials);
24}
25}
Program Run
Enter your fi
rst nam e: Sally
Enter your last nam e: Ryan
S& R
String Operations
String Operations
String Operations
String Operations
Chinese Script