Title: Last Time
1Last Time
- Unary operators
- Casting
- Boolean NOT
- Arithmetic operators
- Other Assignment operators
- Screen I/O (Console and simple GUI)
- Variable Scope
- if statements
2Today
- Reminder Lab 1 and Assignment 1 are posted.
- Assn 1 is due one week from today at 7pm.
- Start out with a warm-up exercise!
- Math class
- Style and Documentation
- Loops
- More exercises!
3Exercise An Easy One
- Prompt the user for an integer.
- Tell the user if the number is odd or even.
4Exercise From Tuesday
- Obtain an outdoor temperature (in degrees
Centigrade) from the user. - If the temperature is less than -40, or greater
than 40 tell him that the temperature is not
legal and exit the program. - If the temperature is gt -40, but less than 0,
display It is cold! Wear a parka.. - If the temperature is gt 0, but less than 15,
display It is cool. Wear a jacket.. - If the temperature is gt 15 and less than 25,
display It is nice! Wear shorts.. - If the temperatuer is gt25 and less than 40,
display It is hot! Seek the beach!.
5The Math Class
- Javas standard mathematical methods are found in
the Math class. They are invoked by naming the
class name followed by the method name, separated
by a period. For example, the sine of a value
can be calculated as - double y Math.sin(x)
- The Math class methods are static, (like the
methods in the System.out class). - This means you can call them directly (without
instantiation).
6The Math Class Cont.
- To get more information on all the methods, look
in the API documentation.
7Example Math.random() Method
- Provides a pseudorandom double value between 0
and 1.0 - How to calculate a random int value between 1 and
1,000, for example?
int randVal (int)(1000 Math.random()) 1
8Programming Style Documentation
- Purpose is to make your code readable (and
debuggable) by you or another programmer who is
familiar with the Java language. - Internal style elements are documentation
(comments), spacing, and descriptive variable
names. - Select the conventions you want to use and be
consistent.
9Programming Style Documentation Cont.
- Comments
- Add a block comment to the top of the class and
at the beginning of each method. Describe
overall purpose of class/method, main algorithm
used, author, date created, and any assumptions
made and/or bugs found. Method comments should
state what parameters are expected by the method
and what the method returns. - Comments for variable declarations, when the name
of variable is not self-explanatory. - Comments at the beginnings of logical blocks of
code. - In-line comments to indicate the closing brackets
of blocks and what they close.
10Programming Style Documentation Cont.
- Spacing (alignment)
- Class definition header starts at column 1, and
closing bracket on column 1. - Indent of about 3 or 4 spaces is adequate.
- Method headers and instance variable declarations
indented once. - Code inside any block, including method code
indented once from alignment of method header, or
outer block.
11Programming Style Documentation Cont.
- Opening can be at the end of a statement
line, or on the line below. - Closing on same column as the column where
the method header is declared, or the statement
containing the opening . is usually by
itself on a line. - Add a comment after to indicate what is being
closed. - If you have an overlong line, it is OK to
continue the line on the line below, but indent
the continued part of the line. (Note do not
try to continue a line in the middle of a String
literal!)
12Programming Style Documentation Cont.
- Spacing (white space)
- Add blank lines before and after methods and
larger logical blocks. - One statement per line. (Longer statements can
be broken onto multiple lines.) - Use a space before , ( and . Use a space
after ) and (unless the next character is
). - No code after or on same line.
- No space after ( or before ).
- Use space after , or in parameter lists or
for loop arguments, but not before. - Put a space on both sides of an binary operator.
- No space before .
13Programming Style Documentation Cont.
- Variable Names
- Also applies to method and class names.
- Follow java restrictions on names
- Use only letters, numeric digits (0 to 9) and the
_ character. - Cannot start name with a number.
- Java is case sensitive!
- Variables and method names usually start with a
lower case character. Class names start with an
upper case character. Constants are all in upper
case. - Variables are usually nouns.
- Methods are verbs or verbs and nouns.
14Programming Style Documentation Cont.
- Be descriptive, but not excessive!
- Examples
- numStudents
- setPassingGrade ( parameter_list )
- Somewhat too long
- flagThatIsSetToTrueIfAProblemArisesWhenThereIsAFul
lMoonOverMyHouseInTheWinterWhileMyProgramIsRunning
- It is OK to use single letter variable names such
as i, j, k for counters in loops.
15Programming Style Documentation Cont.
- The java compiler ignores all white space
including space characters, tabs and carriage
return/line feed characters. - Note that most java keywords are in lower case.
- You will get an error message if you attempt to
use a keyword as a variable name.
16Do
- public class StyleDemo
- public static int someSum (int num1, int
num2) -
- int sum num1 num2
-
- return sum
-
- // end someSum method
-
- // end StyleDemo class
17Dont!
- public class StyleDemo
- public static int s(int l,int l1)
- int Sll1 return S
-
18Repetition or Using Loops
- We will discuss
- while
- do/while
- for
- The for each loop in Java 5.0
- Use of break and continue
19Repetition or Loops
- Suppose we combine a boolean test with some kind
of structure that allows us to branch back up to
an earlier piece of code
if true
if false
etc.
20Repetition - Cont.
- The boolean test determines when to stop the
repetition - as long as the condition is true,
the loop keeps going. - Something inside the looping part must affect
what is tested in the condition - right? What if
it did not - what would happen?
21Repetition - Cont.
- A simple example - suppose we wanted a loop to
execute only 20 times
i 1
if true
if false
i lt 21
i i1
etc.
22Repetition - Cont.
- The number of repetitions is controlled by
changing the limit value for the loop counter -
i in the example on the previous slide. - That example had i increasing by one each time.
The loop counter was being incremented by one. - It could have been incremented by some other
value, 2, 3, or whatever. - You could use something like i i 2 to
increment the counter. - If the counter is decreased in value each time,
it is being decremented.
23Repetition - Cont.
- Suppose, in the previous example, i was
decremented by one instead. What would happen?
i 1
if true
if false
i lt 21
i i - 1
etc.
24Repetition - Cont.
- The dreaded infinite loop!
- The java compiler will not prevent you from
coding a loop like the one shown - it will
compile, and it will run! - And run, and run, and run, and run, and run, and
run, and run, and run, and run, and run - As a programmer, you must be on guard for such
logic errors in your code.
25Reminder - Increment and Decrement Operators
- In loops, expressions like
- j j 1 and
- k k - 1
- are used so often, it is typical to see the
postincrement operator - j is the same as j j 1
- k-- is the same as k k - 1
- You can use either notation.
26while loop
- A java while loop can be used to code the
structure shown in the flowchart above (the
increment one on slide 27) - int i 1
- while (i lt 21)
- // other statements
- i i 1 // or you could use i
- // end while
- The brackets enclose the statements that
are repeated. - (A single statement to be repeated in the loop
does not require the .)
27while loop - Cont.
- Note that java (thank goodness!!!) does not have
anything equivalent to a goto statement. - (And if it did, I would not tell you about it,
anyways!!) - So, you cannot construct a loop with an if
statement and a goto. - An if statement cannot give you repetition, it
only allows you to decide on a single pass
through a branch of code.
28while loop - Cont.
- while loop syntax
- while ( boolean_expression )
- block_of_code
-
- As long as boolean_expression evaluates to true
the statements in the block_of_code continue to
execute. - By mistake, you might write the following - what
would happen? - while ( boolean_expression )
- block_of_code
-
29while loop - Cont.
- The boolean expression tested in a while loop
could be false to start with - int i 40
- while (i lt 21)
- // other statements
- i i 1
-
- In this case, the loop would not execute at all.
- Use a do/while loop if you need a loop that
will always run at least once
30do/while loop
- Syntax
- do
- block_of_code
- while ( boolean_expression )
- Note the at the end of the while statement.
- Since the conditional test is at the end of the
loop, it will always execute the loop at least
once.
31do/while loop - Cont.
- For example, suppose we must obtain a value
between 1 and 100, inclusive, from the user - int aVal 0 // The compiler will force us to
- // initialize aVal
- do
- System.out.print(Enter value between 1 and
100) - // code to obtain a value from the user
- while (aVal lt 1 aVal gt 100)
- As long as the user does not do what he is told,
the loop will continue to re-prompt him for the
correct value.
32for loop
- The kind of while loop shown above
- int i 1
- while (i lt 21)
- // other statements
- i i 1
-
- is used so often, that Java has provided another
looping structure that does all that is shown
above, but needs only one line - for (int i 1 i lt 21 i i 1)
- // other statements
33for loop - Cont.
- Or, as written with an increment operator
- for (int i 1 i lt 21 i)
- // other statements
-
- Syntax
- for (initialization boolean_expression update)
- block_of_code
-
- for loops are used when you know, in advance, the
number of repetitions desired.
34for loop - Cont.
- You dont have to declare the counter inside the
for loop, if you have declared it earlier in your
program. - But if you do declare it in the for statement
then the scope of that variable will only be
inside the loop block.
35for each Loop in Java 5.0
- Often, you will want to visit every element in
a collection, not just a part. - Syntax of the for each loop
- for (type_variable collection)
- // statements
-
- These loops are only used with collections.
36for each Loop in Java 5.0, Cont.
- (We dont know what arrays are yet, but just for
now) - For example, suppose we have an array called
data, containing a collection of double type
numbers, and you want to add them all up - double sum 0
- for (double e data)
- sum sum e // or sum e
37for each Loop in Java 5.0, Cont.
- Equivalent normal for loop
- double sum 0
- for (int i 0 i lt data.length i)
- sum sum datai //or sum datai
-
- The for each loop is a bit easier with arrays,
but is even better suited for other kinds of
collections.
38Loops - Misc.
- Dont declare variables inside loops, as the
repeated declaration process uses up time and
memory unnecessarily. - Loops are often nested - to usually not more than
three levels. For example - int i, j
- int sum 0
- for (i 1 i lt 100 i)
- for (j 1 j lt 10 j)
- sum
- sum would be 1000.
39Loops - Misc. - Cont.
- There is no limit in Java to how many levels you
can nest loops. - It is customary, but not necessary, to use the
variables i, j, k as loop counters. - Loops really demonstrate the strength of
computers as they allow the machine to complete
mind-numbingly boring tasks with perfect
accuracy! - Loops will always be used with any file I/O and
array operations.
40Other Java Keywords Used With Loops
- break and continue
- The continue statement interrupts the execution
of a loop, and returns control to the top of the
loop. - The break statement interrupts the execution of a
loop, and transfers control to the first
statement after the loop.
41Use of continue
42Use of break
43Use of break continue
- Only use these keywords when it makes your code
easier to read. - Avoid the use of more than one break or continue
inside a loop. - If you use a condition to issue a break
statement, then why cant you put that condition
in the loop test? - Overuse of break statements can lead to
spaghetti code - just like the use of goto
statements!
44Loop Exercise 1
- Obtain from the user a positive upper limit.
- Also obtain an increment value.
- Print out all the numbers from 0 to the number
before the upper limit using the increment, one
number per line. For example, if the user
supplies 50 and 20, the output would be - Supply an error message if the input values are
not legal.
0 20 40
45Loop Exercise 2
- Obtain a positive integer number, gt 1 from the
user. If the number supplied is illegal,
continue to prompt him until it is. - Print out all the numbers that divide this number
evenly, including the number itself, starting
from 2. For example, if the user supplies 10,
the output would be
2 5 10
46Loop Exercise 3
- Prompt the user for a positive number of numbers.
- If this number is gt 0, display to the screen this
many prime numbers, starting from 2. For
example, if the user supplies 5, the output would
be
2 3 5 7 11