Download Commenting in Java Programming with “Style” Primitive Data Types

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Commenting in Java
A short comment begins with two adjacent forward slashes, //,
anywhere in a line.
A multi-line comment begins when Java encounters a slash followed
immediately by an asterisk, /*
Finally, there is Javadoc, in which comments begin with a slash and
two asterisks, and continues with a column of asterisks down the left
side on each line. Such comments can be processed so that
documentation is created for display in a web browser.
31
Programming with “Style”
Consistent indentation of statements in “blocks”
Judicious use of comments
Appropriate naming of identifiers
Capitalization rules for identifiers
aReallyLongVariableNameLooksLikeThis
The name of a class (and the associated .java file) begins with uppercase
Constants are all in UPPERCASE
Primitive Data Types
Type
Contains
Default
Size
true or false
false
1 bit
char
Unicode character
\u0000
16 bits
byte
short
int
long
Signed int
0
8 bits
-128
127
Signed int
0
16 bits
-32768
32767
Signed int
0
32 bits
-2147483648
2147483647
Signed int
0
64 bits
-2 63
263 - 1
float IEEE 754 floating pt.
0
32 bits
-3.4 E38 (accuracy +3.4 E38 (accuracy
is 6-7 digits)
is 6-7 digits)
double IEEE 754 floating pt.
0
64 bits
-1.7 E308 (accuracy
is 14-15 digits)
boolean
Min. Value
Max. Value
\u0000
\uFFFF
+1.7 E308
(accuracy is 14-15
digits)
You Must Tell Java the Full Name
of Every Class You Use
Use the import statement, or do a lot of this:
How to “import” Classes
In Java, a package is a collection of classes that have a
related purpose. For example,
the System class and the String class are both in a package named
java.lang which is automatically made available to your program.
Other classes are contained in packages that you must
explicitly import into your programs. For example, to
include the Scanner class from the java.util package, you
would use
java.util
import java.util.Scanner;
Alternatively, to tell Java you might want to use any class in a particular
package, use an asterisk instead of a class name.
35
Getting Keyboard Input
Prior to Java 1.5, there were no built-in classes
for doing simple keyboard input. But now:
Scanner in = new Scanner(System.in);
The input routines are all of the form
aVariable = in.ScannerMethod ();
Some of the different ScannerMethods are:
nextInt()
nextDouble()
nextShort()
…
nextFloat()
nextLong()
nextByte()
36
Find the Average of N #'s
class Average
{
public static void main ( String [ ] args )
{
// how many variables are needed?
}
}
37
if … else
In Scratch,
In Java, the conditional statement is similar:
if ( Boolean-expression ) Java-statement[s]1 ;
else
Java-statement[s]2 ;
Note: Java’s relational operators are evaluated after all arithmetic
expressions have been evaluated; consider
4 * 3 + 2 < 20
%
5 + 3
Drawing “Nested Squares”
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
*
*
.
*
*
*
*
*
*
*
*
*
*
*
*
*
.
*
*
.
*
.
.
.
.
.
.
.
.
.
.
.
*
.
*
*
.
*
.
*
*
*
*
*
*
*
*
*
.
*
.
*
*
.
*
.
*
.
.
.
.
.
.
.
*
.
*
.
*
*
.
*
.
*
.
*
*
*
*
*
.
*
.
*
.
*
*
.
*
.
*
.
*
.
.
.
*
.
*
.
*
.
*
*
.
*
.
*
.
*
.
*
.
*
.
*
.
*
.
*
*
.
*
.
*
.
*
.
.
.
*
.
*
.
*
.
*
*
.
*
.
*
.
*
*
*
*
*
.
*
.
*
.
*
*
.
*
.
*
.
.
.
.
.
.
.
*
.
*
.
*
*
.
*
.
*
*
*
*
*
*
*
*
*
.
*
.
*
*
.
*
.
.
.
.
.
.
.
.
.
.
.
*
.
*
*
.
*
*
*
*
*
*
*
*
*
*
*
*
*
.
*
*
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
39
Nested Squares Program Design
Write a main method that defers the difficult issue of which character
to print.
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.print ("How large is outer edge? ”);
int outerLength= keyboard.nextInt();
for (int row = 1; row <= outerLength; row++)
{
for (int col =1; col <= outerLength; col++) { //somehow, print the correct character! }
System.out.println ();
}
}
40
Nested Squares Key Insight
The big question: is the distance to the closest edge odd
or even?
— print ' * '
Odd
— print ' • ’
outerLength
outerLength
Even
*
*
*
*
*
*
*
*
.
.
.
.
.
*
*
.
*
*
*
.
*
*
.
*
.
*
.
*
*
.
*
*
*
.
*
*
.
.
.
.
.
*
*
*
*
*
*
*
*
41
Printing The Correct Symbol
int distance;
// distance from CLOSEST edge
distance = row - 1;
// distance from top
if (distance > outerLength - row)
distance = outerLength - row;
// from bottom
if (distance > column - 1)
distance = column - 1;
// from left edge
if (distance > outerLength - column)
distance = outerLength - column;
// from right
if (distance % 2 == 0)
System.out.print (" *");
// even number of squares
// from closest edge
else System.out.print (" .");
42
Testing Programs
Use enough test data to try out all possible "paths"
through the program.
Test extreme values and boundary values; don't make
repeated tests of whether the computer is doing
arithmetic efficiently.
Edsger Dijkstra: testing can prove the presence of bugs;
however, except in rare cases where you try every
possible input, it cannot prove the absence of bugs.
43
Testing, continued
Example: calculate cost of a taxi trip
Distance (miles)
Cost
Less than 40
$50
40 to 100
$45, plus $9 per mile excess over 40
Over 100, up to
2000
$190, plus $8 per mile
excess over 100
Over 2000
$1,550
The following values test all cases:
Not needed:
44
The Perils of Overflow
Java uses 32 bits (4 bytes) for each int. This permits 232
different values. The precise range is
Integer.MIN_VALUE (which equals -2,147,483,548 = -231 ) to
Integer.MAX_VALUE (which equals +2,147,483,547 = 231 - 1)
Similar limits can be found for other data types. E.g.,
Double.MAX_VALUE equals 1.7976931348623157 E
308
See Overflow.java and https://youtu.be/MVI87HzfskQ
45
Floating-Point Imprecision
Floating-point expressions are formed using float/double values
and the operators + , –, * , /
If any floating-point operand is present, all ints are converted
to floating point numbers, and the whole expression is of type
double! For example,
2.57 / 9.43 * 2e2
2 + 4 * 3 – 1.0
Floating-point arithmetic on a computer is only approximate; it
is usually meaningless to test for equality of expressions of type
float/double.
Comparisons should use < <= >
Consider EqReal.java, which computes
>=
i=1
Σ 0.1
10
46
Recipe for baking 20 cookies:
Mix the following ingredients in a bowl:
•4 cups flour
•1 cup butter
•1 cup sugar
•2 eggs
•40 bags chocolate chips ...
Place on sheet and Bake for about 10 minutes.
Recipe for baking 40 cookies:
Mix the following ingredients in a bowl:
•8 cups flour
•2 cups butter
•2 cups sugar
•4 eggs
•80 bags chocolate chips ...
Place on sheet and Bake for about 10 minutes.
47
Parameterized Recipe
Recipe for baking 20 cookies:
Mix the following ingredients in a bowl:
• 4 cups flour
• 1 cup butter
• ...
Recipe for baking N cookies:
Mix the following ingredients in a bowl:
• N/5 cups flour
• N/20 cups butter
• N/20 cups sugar
• N/10 eggs
• 2N bags chocolate chips ...
Place on sheet and Bake for about 10 minutes.
48
Parameters
Up to now we have defined only parameterless methods,
though we have used built-in methods that have parameters.
Consider a Scratch 2.0 example:
formal
parameter
actual
argument
49
Parameters in Java Methods
A method can accept multiple parameters (separated by , )
When calling it, you must pass an actual value for each parameter.
Declaration: static void methodName ( type1 param1, ..., typen paramn )
{
Java statement[s] }
Call: methodName (expr1, expr2, ... , exprn);
50
Multiple Parameters Example
public static void main (String [] args) {
printNumber (4, 9);
printNumber (17, 6);
printNumber (8, 0);
printNumber (0, 8);
}
// what output does this program produce?
static void printNumber (int number, int count) {
for (int i = 1; i <= count; i++) {
System.out.print(number);
}
System.out.println();
}
51
A "Parameter Mystery" Problem
class ParameterMystery {
public static void main(String[] args) {
int x = 9;
int y = 2;
int z = 5;
mystery (z, y, x);
mystery (y, x, z);
}
static void mystery (int x, int z, int y) {
System.out.println (z + " and " + (y - x));
}
}
52
Song Generation
How to print the words for "The Ants Came
Marching” by observing a basic pattern:
The ants came marching 1 by 1, hurrah! Hurrah!
The ants came marching 1 by 1, hurrah! Hurrah!
The ants came marching 1 by 1,
The little one stopped to suck his thumb.
And they all go marching down.
To the ground. To get out of the rain!
(Boom, boom, boom ... )
The ants came marching 2 by 2, hurrah! Hurrah!
The ants came marching 2 by 2, hurrah! Hurrah!
The ants came marching 2 by 2,
The little one stopped to tie his shoe.
And they all go marching down.
To the ground. To get out of the rain!
(Boom, boom, boom ... )
…
53
Song Generation, continued
public static void main (String [] args)
{
verse (1, "suck his thumb.\n");
verse (2, "tie his shoe, \n");
verse (3, "climb a tree, \n");
…
…
}
// see MarchingAnts.java
54
The boolean Data Type
The boolean data type is named after the
mathematician George Boole (1815-64), a pioneer
in the study of formal logic.
Some simple examples of boolean expressions
(b*b - 4.0*a*c) >= 0.0 // non-neg discrim.
(year % 100) == 0
// beginning of a century
One can also declare and use boolean variables and parameters.
55
Lines and Boxes Example
Consider the following main method:
public static void main( String [] args)
{
line (13, '*', true);
line (7, '/', false);
line (35, '%', true);
System.out.println();
box (10, 3, '*');
box (5, 4, '=');
box (20, 7, '$');
}
// see Boxes.java
56
Exchange Value of 2 Variables
Sample Initial
Situation
a
17
b
4
Sample Final Situation
a
4
b
17
Intended effect
final value of a becomes the initial value of b
final value of b becomes the initial value of a
Tempting, but wrong:
a = b;
b =a;
// now a is ???
// b is ???
What’s the solution?
57
Arguments are Passed “By Value”
Define a method to exchange the value of two variables
of a primitive type, e.g., static void swapInts (int a, int b)
{
int saveA = a;
a = b;
b = saveA ;
}
What happens if a main method contains
int x = 17;
int y = 35;
swapInts ( x, y);
58
How Methods “return”
static void foo()
{
static int
voidbar()
bar()
_____________;
_____________;
{
_____________;
_____________;
_____________;
…
…
_____________;
_____________;
int n =
bar();
_____________;
_____________;
}
}
_____________;
return;
return intExpr ;
Efficiently Computing a Value
The number of ways of selecting a subset of i objects
from a set of n is
n
Ci
n!
n
=
i
=
i! * (n - i)!
Why is the above computationally inefficient? How can
it be improved?
(See Combin.java)
60
Logical Operator:
To execute code only if both of two (or more) conditions
are true, put && or & between the conditions.
Example: to test whether integer n satisfies the inequality 4 < n <= 9 use if (4 < n && n <= 9) { …
}
A “truth table” formally defines && :
p
q
p && q
false
false
false
false
true
false
true
false
false
true
true
true
61
Logical Operator:
If at least one of two (or more) conditions need be true,
use the "logical Or” operator, || or |
Example: if (age < 16
|| age > 65) { System.out.print ( "Not in workforce");
}
A “truth table” formally defines || :
p
q
p || q
false
false
false
false
true
true
true
false
true
true
true
true
62
Logical Operator:
Sometimes you may want to invert a condition
with ! (logical negation)
This operator takes a single boolean expression and evaluates to true
if that condition is false, and to false if that condition is true.
Occasionally useful are “DeMorgan’s Laws”
! ( a && b )
is the same as …
! ( a || b )
is the same as …
Confusing AND with OR
On the 2015 tax return it states you can claim single-filing
status if any one of the following is true:
You were never married.
OR
You were legally divorced on 12/31/15.
You were widowed before 12/31/15 …
Later on it says you can claim the more advantageous
status of married filing jointly if all 5 of the following are
true:
64
Confusion, continued
(a) Your spouse died in 2103 or 2014 and you did not
remarry in 2015.
(b) You have a child whom you can claim as a dependent
(c) That child lived in your home for all of 2015
AND
(d) You paid over half the cost of keeping up your home
for this child
(e) You filed (or could have filed) a joint return with
your spouse the year he or she died
See http://handbook.fas.harvard.edu/book/
computer-science
65
Using a boolean Variable
Problem: Input a student GPA at the end of 5 consecutive semesters,
print the average AND whether or not the GPA increased every term.
Top-down design:
Initialize sum ;
Initialize test for increase ;
for (sem #1 up through sem #5) { input the GPA
update the sum
test for continued increase
}
print average GPA ;
print whether GPA increased each semester ;
66
Boolean Variables, continued
We need several variables:
double gpa;
// today's GPA
double sum;
// sum of GPA’s
boolean
increasing;
double oldGpa;
// yesterday’s GPA
int semester;
// controls the FOR
How should these variables be initialized?
See file Gpa.java
67
Boolean Variables, finale
Next, we design the main loop
for (int semester= 1; semester <= N; semester++)
{
oldGpa = gpa; gpa = keyboard.nextDouble ();
sum += gpa; if (
???
}
Once increasing turns false it stays false!
68
The Fibonacci Sequence
Leonardo Pisano, better known as Fibonacci, lived 1170-1250 in what is now Pisa, Italy, and played an important role in reviving ancient mathematics; he also made significant contributions of his own.
The Fibonacci Sequence is
f0
f1
f2
f3
f4
f5
f6
f7
0
1
1
2
3
5
8
13
It is defined by induction: f0 = 0,
f1 = 1,
fn = ???
69
Computing Fibonacci #’s
How do we compute the “next” Fibonacci number? Clearly
we need at least two variables. E.g., to compute f7:
highest
nextHighest
8
before
5
13
after
8
The problem: if we first do
highest = highest + nextHighest ;
we lose the old value of highest! What if we first do
nextHighest = highest; ???
70
Fibonacci Solution #1: Fib1.java
Save the sum in a “temporary” variable.
tempSum = highest + nextHighest;
nextHighest = highest ;
highest = tempSum ;
and we're ready for the next round.
tempSum
highest
13
nextHighest
13
8
5
8
71
Fibonacci Solution #2: Fib2.java
Consider using two variables, but with the “next”
Fibonacci number alternating between the two.
oddFib
0
1
1
3
3
+
+
+
+
1
evenFib
1
2
2
5
72
Operator Precedence, part 1
[ ]
.
( … )
++, --
array indexing
object member reference
method invocation & expr evaluation
L
to
R
postfix increment, decrement
++, --
+, -
~, !
new
( type )
prefix increment, decrement
unary plus, minus
bitwise NOT, logical NOT
object instantiation
type-cast
R to L
*, /, %
multiplication, division, remainder
L to R
R to L
73
Operator Precedence, part 2
+
<<, >>
>>>
<, >, >=, >=
instanceof
==, !=
&
^
|
&&
||
addition and string concatenation
subtraction
left shift, right shift
right shift with zero fill
less-than, greater-than, etc.
type comparison
equal, not-equal
bitwise AND, boolean AND
bitwise XOR, boolean XOR
bitwise OR, boolean OR
logical AND
logical OR
L to R
L to R
L to R
L to R
L to R
L to R
L to R
L to R
L to R
Operator Precedence, part 3
? :
conditional operator
=
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=
assignment
addition / string concatenation
subtraction, then assignment
multiplication, then assignment
division, then assignment
remainder, then assignment
left shift, then assignment
right shift (sign), then assignment
right shift (zero), then assignment
bitwise / boolean AND, assignment
bitwise / boolean XOR, assignment
bitwise / boolean OR, assignment
75
R to L
R to L
74
Math Class Methods That
Return Values
See http://download.oracle.com/javase/7/docs/api/index.html
for additional information:
static double Math.random()
static double Math.sqrt (double value)
static int Math.max (int a, int b)
static long Math.max (long a, long b)
static float Math.max (float a, float b)
static double Math.max (double a, double b)
// similarly for Math.min, Math.abs
static double asin (double angle)
static double log10 (double a) …
76
“Random” Numbers
For many simulations, games, etc. it is useful to have
“random” numbers.
The best we can do is to produce psuedo-random numbers, generated
by a deterministic method.
In applied mathematics, the name "Monte Carlo"
method of solving problems by means of experiments
with random numbers.
77
Random # Generation
The popular linear congruential algorithm was introduced by D. H.
Lehmer in 1949. (See Knuth,Vol. II, chapter 1.)
xn+1 = ( a * xn + b ) % m
generates the (n + 1)st random int from the nth.
Example with m = 8, a = 5, b = 3.
x1= 2 (arbitrary "seed")
x2 = (5 • 2 + 3) % 8 =
x3 = (5 • 5 + 3) % 8 =
x4 = (5 • 4 + 3) % 8 =
x5 = (5 • 7 + 3) % 8 =
x6 = (5 • 6 + 3) % 8 =
x7 = (
5
4
7
6
1
78
Working with Math.random()
The built-in method Math.random() uses a linear
congruential method, and always evaluates to a double
greater than or equal to 0.0 but less than 1.0
Initially, the "seed" value of this random number
generator is the system's current time, so you get a
different sequence every time you run your program.
To make the sequence reproducible, learn about the
class java.util.Random
See program Randemo.java for two examples.
79
Experiment to Estimate π
(0, 1)
See A History of PI,
by Petr Beckmann, page
13. This book is
published by The Golem
Press (New York, 1971).
E1
E2
E3
E4
(1, 1)
E5
E6
E7
(1, 0)
80
Formatted Output Using printf
Boring
System.out.printf(“format
string”, expr1, expr2, … exprn);
Another advantage to using Java ≥ vers. 1.5 !
The format string contains ordinary characters and “placeholders”
that tell how each value should be printed.
Digression …
Each placeholder begins with a % character and ends with a letter that
indicates the format type. Flags and width specifiers are options that
indicate exceptions to the default output.
81
Placeholders Used in printf
Code
Type
Example
%d
signed Decimal integer
123
%x %X unsigned Hexadecimal integer 7b 7B
%o
unsigned Octal Integer
173
Fixed
floating-point
12.3
%f
Exponential floating-pt.
1.23E+01
%e
Output a percent sign
%
%%
String
Tax=
%s
%n
platform-specific newline
82
Format Flags Used in printf
(they appear right after the %)
Meaning
Example
-
Left justification
1.23 followed by
spaces
0
Show leading zeroes
000 1.23
+
Show a plus sign for positive numbers
+1.23
(
,
^
Enclose negative #’s in parens
(1.23)
Show decimal separators
12,300
Convert letters to uppercase
1.23E+01
Flag
83
printf Width Examples
%Wd
integer, W characters wide, right-aligned
%-Wd integer, W characters wide, left-aligned
%Wf
real number, W characters wide, right-aligned
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 10; j++) {
System.out.printf("%4d", (i * j));
}
System.out.println();
// end the line
}
84
printf Precision
%.Df
real number, rounded to D digits after decimal
%W.Df
real number, W chars wide, rounded to D
digits after decimal
%-W.Df real number, W wide (left-align), rounded to
D digits after decimal. What does the following print?
double gpa = 3.253764;
System.out.printf("Your GPA is %.1f\n", gpa);
System.out.printf("More precisely: %8.3f\n",
gpa);
85
Iteration Using while
The while permits "indefinite" looping. The syntax:
while ( boolean expr ) Java instruction[s];
The semantics: boolean expr gets evaluated. If true, the
Java instruction[s] are executed; then we start over
again by checking the boolean expr . The Java
instruction[s] may be executed any number of times.
If boolean expr is false initially …
After the while loop terminates, boolean expr …
If executing Java instructions[s] does not make it possible
for boolean expr to become false (when it started off true), …
Introducing do-while
Sometimes we want to execute the statements in a loop at least
once before testing the condition. This can be achieved via
do
{ Java-statement1 ;
Java-statement2 ;
…
Java-statementn ;
} while ( condition );
On exit, condition must be false!
87