Decisions




       Nothing is more difficult, and therefore more precious, than to be able to decide.
       -- Napoleon Bonaparte







Review Exercise: Given a String variable myString which has already been initialized, declare a String variable part and assign it to contain the string consisting of the first 5 characters in myString.

Review Exercise: Write a method that takes a Graphics object g, a background Color backColor, a drawing Color penColor, and draws a starburst:


starburst


Review Exercise: Write a method sillySubstring that takes a string s and returns a string consisting of the first character of s concatenated with the uppercase version of the last 3 characters of s.
That is, sillySubstring("avocado") returns the string "aADO".



To Execute or not to Execute (a Statement), that is the question.




A conditional statement allows us to choose which statement(s) in our program will be executed next.


Example:
if (it is raining)
   Carry an umbrella


The expression - the condition - inside the parentheses is either true or false.



Scanner reader = new Scanner(System.in);
System.out.print("Please enter your exam score: ");
int grade = reader.nextInt();
if(grade > 95)
{
   System.out.println("You made a high A!");
}

The condition, or expression inside the parentheses, is a boolean value - it is either true or false.





The if statement



Syntax:
if(<condition>)
{
    <statement(s)> // called body of if statement
}




Example:
int numberOfBags = 3;
...
if(numberOfBags > 2)
{
   System.out.println("You can only carry on 2 pieces of luggage");
}


Note: As with for loops, when the body of the if statement is only one statement, the curly braces can be omitted:

if(numberOfBags > 2)
   System.out.println("You can only carry on 2 pieces of luggage");





Example:
int theAreaCode = 512;
...
if(theAreaCode = = 512) // test for equality
{
    System.out.println("You live in Texas");
}







Relational Operators




Operator
Meaning
Example
Value
 = =
 equal to
 3 == 2 + 1
 true
 <=
 less than or equal
 5 <= 2 + 3
 true
 <
 less than
 20 < 10
 false
 >
 greater than
 20 > 10
 true
 >=
 greater than or equal
 20 >= 20
 true
 !=
 not equal
 3 != 4
 true




Example: true or false?
3*(2+4) >= 11 - 6/2

Examples:
boolean test = (13 > 15); // test is false

boolean test2 = (101 >= 99); // test2 is true
boolean test3 = (13 == 13); //test3 is true

 8 >= x >= 2   // error
(8 >= x) && (x >=2)   // true if x is between 8 and 2







Logical Operators






The logical operators:
AND (&&)
OR (||)
NOT (!)





Examples:
int i = 14;
int j = 18;
char c1 = 'e';
char c2 = 'h';

System.out.println("i<j is " + (i<j)); // output: i<j is true
System.out.println("i < j && i == i is " + ((i < j) && (i == i)));
    // output: i<j && i == i is true
boolean test = !(i < j); // test is false
boolean test2 = (c1 == c2); // test2 is false
boolean test3 = (i<j) || (c1>c2); // test3 is true
boolean test4 = (i<j) && (c1 > c2); //test 4 is false




Note about Strings


Instead, use the equals() method to determine if 2 Strings are the same:
String h = "hello";
boolean test = h.equals("hello"); // test is true
boolean test2 = "hello".equals(h); // test2 is true

To compare strings for equality except for case differences, use equalsIgnoreCase():
String name1 = "Elvis Presley";
String name2 = "eLvis presley";
if(name1.equalsIgnoreCase(name2))
    System.out.print("Same name!");








The if-else statement


Choose one of two actions to carry out

Syntax:
if(<condition>){
   // action1
}
else {
   // action2
}

When an if-else is executed, the condition is evaluated first. If the condition is true, then action1 is executed. Otherwise action2 is executed.




Examples:
int num = 28;
...
if ((num % 4) = = 0)
    System.out.println(num + " is divisible by 4");
else
    System.out.println(num + " is not divisible by 4");






Important Note about Comparing Floating-Point Numbers


Consider the following code:

double root = Math.sqrt(2);
double diff = root*root - 2; // we expect diff to be 0
 
if(diff == 0)
   System.out.println("sqrt(2)^2 - 2 is 0");
else
    System.out.println("sqrt(2)^2 - 2 is " + diff);



Output:
sqrt(2)^2 - 2 is 4.440892098500626E-16



You should compare whether floating-point numbers are "close enough", rather than exactly equal. Roundoff errors are unavoidable.



Exercise: Write a program that reads two floating-point numbers from the keyboard, and prints a message indicating whether they are within epsilon of each other, where epsilon is the program-defined constant 0.0001.

Exercise: Write a program that reads a string from the keyboard, and prints a message indicating whether or not each of the vowels a, e, i, o and u occur in the string.




Nested if/else Statements

Chain together if and multiple else blocks to choose one of several actions to take.

Syntax:
if(<condition1>)
{
    <statements>; // action1
}
else if (<condition2>)
{
    <statements>; // action2
}
else if (<condition3>)
{
    <statements>; // action3
}
else
{
    // optional else block
    <statements>; // action4
}

Example:
int grade = reader.nextInt();
if(grade >= 90)
     System.out.println("You made an A!");
else if (grade >= 80)
    System.out.println("You made a B!");
else if (grade >= 70)
    System.out.println("You made a C!");
else
    System.out.println("D or F - work harder next time.");


Note: The else block is optional.


Example: If i isn't greater than 0, no action taken.
int i = ... ;
if (i >3)
    System.out.println("greater than 3");
else if (i > 2)
    System.out.println("greater than 2, but less than or equal to 3");
else if (i > 0)
    System.out.println("positive, and less than or equal to 2");






Removing Redundancy from if-else Blocks



int amount = ... ;
if(amount > 500) {
    System.out.println("Funds remaining: " + amount + " left.");
    System.out.println("Reasonable balance");
    System.out.print("How much do you want to deposit? ");
    deposit = reader.nextInt();
}
else if(amount > 100) {
    System.out.println("Funds remaining: " + amount + " left.");
    System.out.println("Getting low");
    System.out.print("How much do you want to deposit? ");
    deposit = reader.nextInt();
}
else {
    System.out.println("Funds remaining: " + amount + " left.");
    System.out.println("Urgent - account balance is very low");
    System.out.print("How much do you want to deposit? ");
    deposit = reader.nextInt();
}







After Factoring - Less Redundant Code



int amount = ... ;
System.out.println("Funds remaining: " + amount + " left.");

if(amount > 500) {
    System.out.println("Reasonable balance");
}
else if(amount > 100) {
    System.out.println("Getting low");
}
else {
    System.out.println("Urgent - account balance is very low");
}

System.out.print("How much do you want to deposit? ");
deposit = reader.nextInt();






Characters in Java


Type char - a primitive type in Java that represents single characters


Note: "a" is a string of length 1, NOT a char.

We can compare characters using <, >, >=, <=, = =. The ordering on digit and letter characters, from least to greatest, is:
0-9  A-Z  a-z

Ex: '1' < '2', '2' < '3'
       'A' < 'a' , 'a'< 'z'



Example: Write a loop that prints the alphabet
for(char letter = 'a'; letter <= 'z'; letter++)
    System.out.print(letter);


Example:
word = scan.next();
if(word.charAt(0) == 'e')
    System.out.println(word + " starts with the letter e");



char vs. int


All char values are assigned integers by computers, called ASCII values.

Example:
'A' is 65, 'B' is 66, 'C' is 67, 'D' is 68, ...
'a' is 97, 'b' is 98, 'c' is 99, ...

Perform arithmetic operations on values of type char - mixed operations with chars and ints are automatically converted to type int:


To convert an int to the equivalent char, use an explicit cast:
(char) ('c' + 1)   // value is 'd'





Pre-defined Character Methods for us to use:
char Character.toLowerCase(char ch) - returns the lowercase version of the character that was passed in
char Character.toUpperCase(char ch) - returns the uppercase version of the character that was passed in

Ex: System.out.println(Character.toLowerCase('A'));
        Output to screen: a



char vs. String

'a' is a char
"a" is a String








Processing Characters


Static methods from java.lang.Character class:


Example:
String word = ...;

if(Character.isDigit(word.charAt(0)))
{
    System.out.println(word + " cannot be a Java identifier, since identifiers do not
       start with a digit");
}


Example:
String name = ...;
// print name with the first letter capitalized
char firstLetter = name.charAt(0);
char capitalFirst = Character.toUpperCase(firstLetter);
System.out.println(capitalFirst + name.substring(1));


Exercise: Go back and revise the code in the above example so that it handles the cases where the length of name is either 0 or 1 correctly.


Exercise: Finish the println() call to print an appropriate message.
String s;
...
// asume s has been initialized
if(Character.isLetterOrDigit(s.charAt(s.length()-1)))
    System.out.println(                          )







More on Comparing Strings


Recall:

The compareTo() method in the String class:

Example:
if("hippo".compareTo("zebra") < 0)
    System.out.println("hippo comes before zebra in alphabetical order");
else if("hippo".compareTo("zebra") == 0)
    System.out.println("hippo and zebra are the same string!");
else
    System.out.println("hippo comes after zebra in alphabetical order");


Note:
If all letters are the same case, then the lexicographic ordering provided by the compareTo() method is the same as alphabetic order. Otherwise remember that in the Unicode character set, all uppercase letters come before all lowercase letters. So "Battle" comes before "ant".



Example:
String name1;
String name2;
...
// assume the String variables are initialized
int cmpValue = name1.compareTo(name2);
if(cmpValue < 0)
    System.out.println(name1 + " precedes " + name2);
else if (cmpValue = = 0)
    System.out.println(name1 + " equals " + name2);
else
    System.out.println(name1 + " comes after " + name2);












Practice Problems


Enter two positive integers: 4  15
4 and 15 are relatively prime
Enter two positive integers: 12 18
2 is a divisor of 12 and 18