Download Java Coding 3

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

Location arithmetic wikipedia , lookup

Law of large numbers wikipedia , lookup

Addition wikipedia , lookup

Arithmetic wikipedia , lookup

Expected value wikipedia , lookup

Elementary mathematics wikipedia , lookup

Transcript
Java Coding 3
Over & over again!
David Davenport
Computer Eng. Dept.,
Bilkent University
Ankara - Turkey.
email: [email protected]
IMPORTANT…

Students…
This presentation is designed to be used in class as
part of a guided discovery sequence. It is not selfexplanatory! Please use it only for revision purposes
after having taken the class. Simply flicking through
the slides will teach you nothing. You must be actively
thinking, doing and questioning to learn!

Instructors…
You are free to use this presentation in your classes
and to make any modifications to it that you wish. All
I ask is an email saying where and when it is/was
used. I would also appreciate any suggestions you
may have for improving it.
thank you,
David.
Repetition

Java repetition statements
while (condition)
statement;
do
statement;
while (condition);
for ( init; condition; update)
statement;

where
 statement is any Java statement
 condition is a boolean expression
The while statement


Does statement while condition true
does statement 0 or more times
while (condition)
statement;
loop
true
condition
false
statement
Examples (1)

Print 5 asterisk characters



Use 5 println statements!
Use a single println statement!
Use a while loop…
starsPrinted is 0
while starsPrinted < 5 do
print a star
add 1 to starsPrinted
print “done”
*
*
*
*
*
done
Examples (1)

Print 5 stars (asterisk characters)



Use 5 println statements!
Use a single println statement!
Use repetition (a loop…)
starsLeftToPrint is 5
while there are starsLeftToPrint do
print a star
subtract 1 from starsLeftToPrint
print “done”
*
*
*
*
*
done
Examples (1)

Print 5 asterisk characters



Use 5 println statements!
Use a single println statement!
Use a while loop…
count = 0;
while ( count < 5 ) {
System.out.println( “*”);
count = count + 1;
}
System.out.println( “done”);
*
*
*
*
*
done
If you print
out count as
well as the
star, what do
you get?
Examples (2)

Read & sum 5 values

by analogy!
sum is 0
count is 0
while __________
count < 5
do
read
read
value
value
addadd
value
value
to to
sumsum
add 1 to count
report sum
5
3
7
4
1
sum is 20
Examples (2)

Read & sum 5 values
Named constant
or ask for & get
value from user
sum = 0;
count = 0;
while ( count < 5 )
{
value = scan.nextInt();
sum = sum + value;
count = count + 1;
}
System.out.println( “sum is ” + sum);
5
3
7
4
1
sum is 20
Examples (3)

Extract design patterns/templates

Counting loop…
count is 0
while count < numberOfRepetitions
process to repeat
add 1 to count

Count, sum or product in loop…
Immediately initialize to 0 (1) before loop
Generic form of while
initialise any variables in condition
while (test condition variable)
do statement & update condition variables;

What happens if you fail to…

Initialise loop variables
• Unpredictable behaviour

Update loop variables
• Infinite loop! (in console app’s use Ctrl-C to exit)

In general…

condition must be falsifiable
by applying update to initial values… need proof!
Proving loops terminate (1)

Do these print “done”?
count = 0;
while ( count < 5 ) {
System.out.println( “*”);
count = count - 1;
}
System.out.println( “done”);
i = 1;
while ( i != 50 ) {
System.out.println( i);
i = i + 2;
}
System.out.println( “done”);
Proving loops terminate (2)

What about this one?
i = scan.nextInt();
while ( i != 1 ) {
if ( i % 2 == 0)
i = i / 2;
else
i = 3 * i + 1;
}
System.out.println( “done”);

Proof that cannot write program to
determine whether every algorithm will halt or not.
(ref. Halting Problem – Alan Turing.)
Reading a set of data

Three approaches
How many? 5
3
5
7
4
1
sum is 20
More?
3
More?
5
More?
7
More?
4
More?
1
More?
sum is
Y
Y
Y
Y
3
Must say
5
“no more”
7
4
1
-1
sum is 20
Y
N
20
Sentinel value
non-data value
marks end of list
Sentinel-controlled input

Sum set of values terminated by -1
sum = 0
read value
while value is not the sentinel do
add value to sum
read next value
print sum

Extract another design pattern
read value
while value is not the sentinel
process the value
read next value
Examples (sentinel input)

Find the average of set of exam scores. Allow user to
enter any number of scores; stop and report the
average when a negative score is entered.

Write a program that allows the user to enter a set of
values. When the user enters zero it should stop and
report the number of positive and the number of
negative values entered.

5, 3, -7, 2, -4, 0  3 positive & 2 negative values entered.

0  0 positive & 0 negative values entered.

9, 2, 8, 0  3 positive & 0 negative values entered.

-4, -8, -3, -5, 0  0 positive & 4 negative values entered.
Examples (sentinel input)

Allow user to enter a limit value, followed by a set of
positive values terminated by a zero. After the user
enters zero, print a message to say whether any of
the values exceeded the given limit or not.
Enter limit: 8
Enter values (0 to stop):
5
2
7
4
0
Limit NOT exceeded.
Enter limit: 10
Enter values (0 to stop):
3
12
7
14
6
0
Limit WAS exceeded.
Questions (1)

Read a set of positive values & report their maximum
after the user enters a negative value. Extend to
minimum.

Allow the user to enter a set of positive values &
report whether they were in ascending order or not.

Write a program that asks the user to enter an integer
number N, then prints a triangle with N lines of stars
or numbers. For example, if N is 4
*
***
*****
*******
1
222
33333
4444444
Questions (2)

Compute PI using the series expansion
PI = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 …)
by evaluating:
(a) a fixed number of terms
(b) enough terms until a specified accuracy is
achieved, e.g. until the value changes < 0.001

For intervals of 0.1 seconds, compute and
print the height of a mass falling from a
given initial height, until it hits the ground.
…other forms of repetition in Java
FOR & DO-WHILE
Java for statements


Same as while loop!
Use as short-hand
counting style loop
for ( init; condition; update)
statement;
Example:
for ( i = 0; i < 5; i = i + 1)
System.out.println( “*”);
init
false
condition
true
statement
update
Questions (1)

Write a program that asks the user to enter
an integer number N, then prints a triangle
with N lines of stars or numbers. For
example, if N is 4
*
***
*****
*******
*******
*****
***
*
1
222
33333
4444444
1
212
32123
4321234
Example

Ask the user for their name, print it out
one character per line, then print “done”.
Enter your name: David
D
for (index = 0; index < name.length(); index++)
a
System.out.println( name.charAt( index) );
v
i
d
for index = 0 to ___________
done.
print charAt index in name
print
“
“
“
“
1st char in name
2nd
“
“
“
rd
3
“
“
“
:
“
“
“
last “
“
“
print charAt 0 in name
“
“
1 “
“
“
“
2 “
“
“
“
: “
“
“
“ last “
“
Using Java methods…

To use, need to know



Method name
Inputs & their types
Output type
output
result type
answer = f( x, y, z );
Method
name
input
parameters
// in Math class
public static double sin( double d)
double d = Math.sin( 0.5);
// in String class…
public String substring( int beginIndex, int endIndex)
// usage…
shortString = longString.substring( 1, 3);
Use ClassName.method(…)
for “static” methods
varName.method(…)
for non-static
methods
Example

Ask the user for their name, print it out
one character per line, then print “done”.
Enter your name: David
D
a
v
i
d
done.
Finally…
From either sequence of characters,
construct a String, reverseName
now do it
in reverse!
Enter your name: David
d
i
v
a
D
done.
Question

Given an integer, print its digits in
reverse sequence, one per line.
Enter integer: 372
2
7
3
done.
Now reconstruct the
reverse integer
Enter an integer: 372
Reversed is: 273
Note: you are not
allowed to use the
power function!
Java do-while statements

Repeat 1 or more times
do
statement;
while (condition);
statement
Example:
i = 0;
do {
System.out.println( “*”);
i++;
} while ( i < 5);
condition
true
false
Examples (do-while)

Data validation

e.g. Read positive value from user
do
ask for “a positive value” and get value
while value is not positive
do {
System.out.print( “Enter positive value: ”);
value = scan.nextInt();
} while ( value <= 0);
// assert: value > 0
Examples (do-while)

Menus -
set of options for user to select from
do
display menu
get selection from user
perform selection
while selection is not exit
print “goodbye”
if selection is SALES then
// do sales things
else if selection is STOCK then
// do stock things
else if selection is ADMIN then
// do admin things
else if selection is not EXIT then
print “invalid selection” msg
ABC Trading Co.
-----------------1 – sales
2 – stock
3 – admin
Select (0 to exit): _