- Relational Operators
- <
binary “is less than”
- >
binary “is greater than”
- <= binary “is less than or equal to”
- >=
binary “is greater than or equal to”
- Logical Operators
- !
unary NOT
- && Binary AND
- ||
Binary OR
- Operands must be Boolean
expressions
- Truth Table
- Short circuit evaluation
- Compiler starts evaluating from the left
and moving to the right.
- As soon as it can determine what the
outcome is going to be, then it will terminate.
- Example
- if(10 < 11 && 11
== 11)
- The compiler will stop evaluating after the 10
< 11
- Boolean Expressions
- De Morgan’s Law
- !(A && B) == !A || !B
- !(A || B) == !A && !B
- Unary operators take precedence
- Try to prove Morgan’s law using the truth
table
- If Statement
- Used when program should perform an operation
for one set of data, but do nothing for all other
data.
- Syntax:
if (condition)
{
//true
block
//executed if
condition is true
}
- Curly braces are optional if true block
contains only one statement.
import java.util.Scanner;
public
class Grade
{
public static void main( String
[] args )
{
Scanner scan = new
Scanner( System.in );
System.out.print(
"Enter a grade > " );
int grade =
scan.nextInt( );
if ( grade >= 50
)
System.out.println(
"pass" );
System.out.println( "Fail"
);
}
}
- Don’t put semi-colons after the
condition
- If Else Statement
- Used when program should perform an
operation when a condition is true for one set of data, and
then do something else when the condition is false another set
of data
- Again, no need for curly braces if only
one statement within condition
import java.util.Scanner;
public
class Divid
{
public static void main(
String [] args )
{
Scanner
scan = new Scanner( System.in );
System.out.print( "Enter the dividend > "
);
int dividend = scan.nextInt(
);
System.out.print( "Enter divisor > "
);
int divisor = scan.nextInt(
);
if ( divisor == 0
)
System.out.println(
"divide by zero" );
else
System.out.println( dividend + " / " + divisor
+ " = " + ( dividend / divisor ) );
}
}
- If Else If Statement
- Used when program should perform an operation
when a condition is true for one set of data, and then
evaluate another operation when the first condition is
false.
import
java.util.Scanner;
public class Smallest
{
public static void main( String [] args
)
{
int
smallest;
int n1, n2,
n3;
Scanner scan = new Scanner(
System.in );
System.out.print(
"Enter the first integer: " );
num1 = scan.nextInt( );
System.out.print( "Enter the second integer: "
);
num2 = scan.nextInt(
);
System.out.print( "Enter the
third integer: " );
num3 =
scan.nextInt( );
if ( n1 <
n2 )
smallest = n1;
else
smallest =
n2;
if ( n3 < smallest
)
smallest
= n3;
System.out.println( "The
smallest is " + smallest );
}
}
- Nested if statements
- Used when program should evaluate
another condition when a condition evaluates to true
- Examples of terminating nested if statements
SEE SLIDES
- Dangling Else
- Testing techniques
- A good test suite executes every statement in
your program (could be exhaustive).
- Comparing doubles/floats decimals
- Give yourself a
threshold
if(Math.abs(dbl1 – dbl2) < .0001) …
- Comparing characters
- Comparisons of characters are comparing the
Unicode number of the character
- Comparing objects
- Comparisons of objects that do not override
the Object.equals method are comparing the instance of object
in memory, not the data of the object
- compare objects use the equals
method.
- Comparing strings
- Strings are objects, so use the equals
method
- You can also use equalsIgnoreCase are defined
in the string class and compareTo – used for
sorting
- Conditional operator
- A shortcut to simplify a simple if else
statement
- Example
String result
= (testString == “help” ? “needs help” : “does not need
help”);
- Switch Statement
- Only accepts character or integer (byte,
short, or int) expression to constants of the same
type.
- Can group case statements
case 1:
case 2:
// do
something
break;
Looping
- Learning how to repeat
an action multiple times
- Event-controlled loops using while
looping techniques
- Simple concepts/algorithms to implement
looping and show syntax
- arrays require complex looping
operations
- Type Safe Input using scanner
- Construct loop
conditions
- Testing techniques - what's best
- do while -
- Count controlled - for loop versus while loop
- while
loop occurs as long as a certain event is true, i.e an EOF is
found.
- for loops are for the times when you know exactly how
many; e.g. all even
#'s between 1-100. You know the limit so
this calls for a for loop.
- Nested loops. sorting algorithms
require three nested loop.
The Grocery Cashier (taken from Java 5 Illuminated text book)
- For
every customer scan items until the divider is found. Then
the cashier calculates total and the process restarts for the
next customer.
- This is what we do for event controlled
loops, i.e. stop scanning at divider, reinitialize for next
customer.
- Start with an initial value and execute and adds
the price to the total.
Looping
- Perform the same
operations on multiple times.
- Initialize - start and do at
least one time, i.e. add price to total at the end results,
then exit and start a new customer.
- for while and
do/while
The while loop
- If you don't know how many
times you have then use a while loop. There needs to be an
event to tell the loop to stop. i.e reading from a file and no
more data in the file is an event to stop.
- This event or
signal tells the execution to stop with a sentinel value or an
end of file.
while loop flow of control
- Initialize
variables - starting clean.
- Condition is evaluated at the
beginning (must be boolean and be true or false) If false, exit
the loop. If true execute the loop body which can be one or
more valid java statements. Once this is finished re-evaluate
the condition and if true continue to do the same thing and do
that until it is
false.
while Loop Syntax
-
Initialize before you start the loop. It's not a compiler error to
not initialize but you may not get clean results.
- Put in
boolean expression execute statements between curly braces
when boolean becomes false, stop.
- Curly braces are not
required if you have only one statement. Just put a semicolon
at the end of the single statement.
- Not putting braces is
correct but logically may make it difficult to read.
- tip:
indent body of while loop. This makes it easier to read.
Some definitions.
- Iteration one execution of the body of the
loop.
- Loop update. You always have to update the condition
that gets evaluated or you get an infinite loop. This is a
logical mistake the compiler does not catch this. For example,
reading a value from the user. While this value does not equal
-1. You need a read statement before the while loop so the
condition can exist so you can start the loop. now in the loop,
read a new value from the user so the loop can decide to
continue or not.
- Loop termination - the event that causes
the loop condition to evaluate to false.
- This code
causes and endless loop.
int i =
0
while ( i < 10); //empty loop body
{
i++ //not in
the loop body
}
- In your lifetime you will write
an endless loop. So syntactically this is okay. The semicolon is
an unintended logical error but you can write one of these and may
need to.
- It's being busy waiting - you're busy but you're
waiting.
Sentinel Controller while loop
- You
always have priming read
- Use data item to get into the loop
but don't forget to read again.
- Omitting the update read may
result in an endless loop.
- Program prints 10 until it crashes
because the initial read is not updated in the loop.
- Next
case. There is no priming read
int input, count = 0;
//input
is not initialized and will give you the value in the memory
now
occupied by "input"
while (input != 10) //10 is
sentinel
{
Systmeout enter integera
input =
scan.NextInt;
count++
}
import
java.util.Scanner;
public class
Echo
{
public static void main( String
[] args )
{
final int SENTINEL =
-1;
int
number;
Scanner scan
= new Scanner( System.in
);
// priming
read
System.out.print(
"Enter an integer, or -1 to stop > "
);
number =
scan.nextInt( );
while ( number != SENTINEL
)
{
//
processing
System.out.println( number
);
// update
read
System.out.print( "Enter an integer, or -1 to stop > "
);
number = scan.nextInt(
);
}
System.out.println( "Sentinel value detected. Goodbye"
);
}
}
- Notice that SENTINEL is static. This could not
be but it makes it more readable.
Reading from a text
file.
initialize variables
while ( there is more
data in the file)
{
read the next data item
process the
data
}
report the results
- You know there is more data in the file as
long as you don't have an EOF.
Setup for reading from a
file
- file class (java.io package)
- File (String
pathname) constructs a file objec with the file name pathname A
scanner constructor for reading from a file Scanner ( File file ).
Example:
File inputFile = new File(
"input.txt" ) // not path indicates a relative
path.
scanner can not scan from this:
Scanner scan = new Scanner( inputFile )
java.io
does have to imported. only lang is automatically
available.
Scanner Class hasNext Method
- Returns
true if there is more data to read or false when it's gone. this
eliminates the need for a priming read.
- IO exception throws
IOException because with outside media the file may be transient.
Java lets you know this can't work by giving this error.
-
Always use this exception notice the main method ins this example
is throwing the exception because the file is being declared in
main. You will get a compiler error if there is IOException.
-
This is a part of making your program reliable - to keep your
program or computer from crashing.
Looping
Techniques
Accumulation
- get a running total. get
a set of values and keep adding together. Start with 0, add to the
total
import
java.util.Scanner;
public class
Calculator
{
public static void
main( String [] args )
{
final int SENTINEL =
0;
int
number;
int total =
0;
Scanner scan = new
Scanner( System.in );
System.out.println( "Welcome.\n"
);
System.out.print(
"Enter 1st #" + " or 0 for the total > "
);
number =
scan.nextInt( );
while (
number != SENTINEL )
{
total +=
number;
System.out.print( "Enter the next number" + " or 0 for the total
> "
);
number = scan.nextInt(
);
}
System.out.println( "The total is " + total
);
}
}
- A logical error would be total = number and
not total= total + number doing an average you would put in a
counter for the number of entries and you put in an iterator and
once out divide total by the count.
- What if user enters
his name? scan.nextInt assumes users in well behaved we need to
guard against user stupdity, you can do this in before the class.
You can test before you assign it to score. You can ask them to
reenter.
- line 42 you need to check to make sure CountScores
is not 0 because it's the divisor and you can't divide by
0.
- If you divide int/int you get an integer. You need to
typecast the
result to a double to get this correct.
double average = (double)
(tot)/(count);
What's the difference between
this:
double average = (double)
(tot)/(count);
and this?
double
avg = tot/(double)count;
These are not the
same:
remember int tot,count
you typecast either tot or
count and get the same thing but you can't typecast the third
one and it doesn't produce correct:
tot
= 90 count = 7
1. avg = 90/7.0
so you get 12.15
2. avg = 90.0/7 so you get 12.15
3. avg =
(90/7) so you get 12.0 so you lose the
1.5
Finding Maximum and minimum.
- Reading
numbers and getting max/min
- Read first item and consider it
to be max and compare each new one against max if less than then
you switch.
Example Menu Program
- Endless loop
because of the conditions which are always S or s. So you need to
do Demorgan's law and then test against the negation.
The
do/while loop syntax
- You always gain one statement. The body
of the loop is executed at least once.
- Test at the end of the
condition.
The for loop
- When you know the number of
interactions.
- The for Loop Syntax
for (initialization; loop
condition; loop update)
{
// loop
body.
}
- You can have one or more statements in the
initialization phase. It can be any statement.
- Loop update
can be any statement
- First execute initial then do it ONCE.
Then test condition if true do the body, if false stop, first
iteration of the body you go and do the loop update and check the
loop body, update, condition
- All three parts are option but
all semicolons are required
This loop for(;;) is a valid loop
- this is the "for" ever for loop. This is for event controlled
looping.
- You can also do this: monitoring a telephone
line:
for (;;)
{ do stuff
}
In program do an if statement that will tell it
how to exit. but you keep looping for ever.
Phone switch
monitors all of its lines but it checks serially if it's off.
There is a nanosecond delay. That's a forever loop that breaks
when you request service by picking up the phone.
Example
1 Find Sum of 100 integers
import
java.util.Scanner;
public class
Sum100Numbers
{
public static void
main( String [] args )
{
int total = 0; // stores the sum of the 5
numbers
int number; // stores the
current input
Scanner scan = new Scanner(
System.in );
for ( int i = 1; i <= 100;
i++ )
{
System.out.print( "Enter an
integer > "
);
number = scan.nextInt(
);
total += number; // add input
to total
}
System.out.println( "The total
is " + total );
}
}
Example
2
public class
EvenNumber
{
public static void main(
String [] args )
{
String toPrint =
"";
for ( int i = 0; i
<= 20; i += 2 )
{
toPrint += i + " ";
}
System.out.println( toPrint );
}
}
- Increment does not have to go by just one
can be more, could be reading from a file, could be
decrement.
- Condition part must be a boolean.
%
Example 3
import
javax.swing.JOptionPane;
public class
Backwards
{
public static void main(
String [] args )
{
String original,
backwards = "";
original = JOptionPane.showInputDialog( null,"Enter a sentence"
);
for ( int i =
original.length( ) - 1; i >= 0; i--
)
{
backwards += original.charAt( i
);
}
JOptionPane.showMessageDialog(
null,
"The sentence backwards is: " + backwards
);
}
}