Welcome to Lesson 6!


Learning Objectives

By the end of today's class, you should know...

  • What are escape sequences and how are they used when creating Strings?
  • How do you create decision points in your program using if statements?
  • How do you write programs where there are exactly two alternatives?


1. Lesson 5 Practice Exam Questions


Part 1:
  • Write a complete user interaction as follows (4-5 lines of code only!):
  • Declare a new Scanner variable named readin, and connect it to the console keyboard.
  • Prompt the user to enter his or her first name with a message like Enter your first name:
  • Declare a String variable named first_name.
  • Read in the user input and store it as the first_name variable
  • Close the Scanner.
  • Now alter the above statements to read in the user's full name.
  • What would need to change if you were reading in an integer value? A double value?
Part 2:
  • Given the following String variable:

    String statement = "Life is beautiful";

  • Do the following to the String:
    • Print out the String in all capitals
    • Print out the length of the String
    • Print out the first and last character of the String.

2. Wrapping Up Strings: Escape Sequences

  • Java can access control codes and hard-to-print characters using escape sequences
  • Backslash (\) directly in front of a certain character tells the compiler to escape from the normal interpretation
  • The following table has some nonprinting and hard-to-print characters

Sequence       
Meaning
 Example
\"
Double Quote
 String saying = "\"When you fall, I will be there to catch you.\" - Love, the floor.";

\'
Single Quote
 char quote = '\'';
\t
Tab
 System.out.println("Year\tRainfall\tLocation");
 \n New Line
 System.out.print("Welcome!\n\nEnter your id#: ");


  • We will practice with escape sequences in our homework.

3. Introducing If Statements

Teaching Computers to Make Decisions

  • The programs we have worked with so far simply execute a list of instructions
  • We arrange our command statements in a particular order to get the result we want
  • When the program reaches the end of the list of instruction, it stops
  • Except for differences in the input, these programs always work the same way:


  • Our programs up until now (left) followed a linear sequences of steps. With if statements, we can create decision points in our code (right).
  • To create more interesting and useful programs, we need our programs to make decisions and carry out different actions
    • For example, if the user enters an incorrect value, we want our program to warn the user with an error message
    • However, if the user enters a correct value, we do want to print "Correct!!"
System.out.print("Enter a guess: ");
int guess = input.nextInt();

if (guess == 7) {
    System.out.println("Correct!!");
}

  • For our programs to make decisions and carry out different actions, we use statements to change the flow of control
  • Flow of control (or control flow) refers to the order in which programs execute instructions
  • By changing the flow of control based on a test condition, we can teach the computer to make decisions
  • We will look at two major ways to change the flow of control:
  • Conditional (selection) statements
  • Loops (repetition) statements
  • In this section, we will look at how to use the conditional statements:if if...else
  • Later will look at more selection statements and how to use the loop statements
Video: Bill Gates explains If statements

The Value of a Relationship

  • Before we discuss if-statements we need to talk about relationships
  • A relationship is a way to compare two numbers or other entities
  • For example:

guess == 7

  • The above example is called a relational expression

count <= 7


  • A relational expression uses a relational operator to compare two entities like numbers or variables
  • We have used relational operators in algebra and Java relationships are similar
  • The following table shows the relational operators of Java

Relational Operators

Math Name Java
Examples   Result Notes
= Equal to == 5 == 10
2 == 2
false
true
Do not confuse with = which is assignment.
Not equal to != 5 != 10
2 != 2
true
false
The ! is like the line that "crosses through" the equal sign.
< Less than < 5 < 10
5 < 5
5 < 2
true
false
false

Less than or equal to <= 5 <= 10
5 <= 5
5 <= 2
true
true
false
Be careful not to write =<. Code the symbols in the order people normally say them.
> Greater than > 5 > 10
5 > 5
5 > 2
false
false
true

Greater than or equal to >= 5 >= 10
5 >= 5
5 >= 2
false
true
true
Be careful not to write =>. Code the symbols in the order people normally say them.

Using if Statements

  • The simplest control-flow statement is an if statement
  • We use an if statement to select whether or not to execute a set of statements
  • An if statement has two parts: a test and a body
  • The body can have zero or more statements
  • The statements in the body execute if and only if the test evaluates to true
  • If the test condition evaluates to false, the computer skips the code
Syntax:

if (test) {
    statement1;
    statement2;
    ...
}

Where:
  • test: the test condition to evaluate
  • statementX: the statements to execute depending on the test
  • For example:
      if (7 == guess) {
        System.out.println("*** Correct! ***");
    }

  • You can visualize an if statement using the following diagram:



image source
  • You can see an example of an if statement in the following example
  • Example Program With an if Statement

import java.util.Scanner;

public class Guess {
public static void main(String[] args) {
int guess;
Scanner input = new Scanner(System.in);
System.out.println("I'm thinking of a number between 1 and 10"
    + "\nCan you guess it?\n");
System.out.print("Enter your guess: ");
guess = input.nextInt();

if (7 == guess) {
System.out.println("*** Correct! ***");
}
input.close();
}
}


  • About those Curly Braces
  • Technically, the if statement affects only the single statement that follows you can leave off the curly braces:
if (x < 5)
System.out.println("x is less than 5!");

  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the body
  • Curly braces are not always required, but the best practice is to always include them
Incorrect curly braces:

public class Braces {
public static void main(String[] args)
{
int x = 3;
if(x < 5)
{
//Incorrect indentation:
System.out.println("x is less than 5!");
}
}
}

Correct curly braces:

public class Braces {
public static void main(String[] args)
{
int x = 3;
if(x < 5)
{
//Correct indentation:
System.out.println("x is less than 5!");
}
}
}

Activity 6.1: Is Your Number Even? (10pts)

  • One of the principle uses of the modulus operator is determine whether a number is even or odd.
  • What is the difference between an even and odd number?
    • How can we use division to figure out if a number is even or odd?
  • Open up Eclipse and create a new project called Activity6
    • Add a class named Even
  • At the top of your program, add a block comment to contain your name and section information:
/**
* @author YOUR NAME HERE
* CIS 36A, Activity 6.1
*/
  • Now, between the curly braces of the main method declare an integer variable named testNum. Then declare a second integer variable to store the remainder. Call this variable remainder.
int testNum;
int remainder;


  • Also declare a Scanner variable to read user input from the keyboard (System.in) later in the program:
Scanner in = new Scanner(System.in);

  • Next, add a System.out.println statement to welcome the user to our program and explain its objective.
System.out.println("Welcome!\n\nEnter a number and "
    + "I'll report back if it's \"even\"!\n");

  • Now, prompt the user to enter a whole number.
System.out.print("Please enter a whole number: ");
  • Next, read the user input and store it in the testNum variable. Complete the following statement and add it to your program:
testNum = ????;

  • Calculate whether the number is even or odd using the modulus operator. Add the following statement to your program.
remainder = testNum % 2; //pronounced testNum "mod" two
  • Below the line where you calculate the remainder, add the following if statement to determine whether the number is even, and, if so, report your result to the user.

if (remainder == 0 ) {
System.out.println(testNum + " is even.");
}

  • Test your code to make sure it is working. Is this program satisfactory?
    • Hint: No. We will improve on this program for Activity 6.2.
    • For now, submit it as is - with only one if statement (and no else statements)
  • Submit your program to Canvas.

4. Using if-else Statements

  • Sometimes we want to choose between two possible actions, as in the below pseudocode:
If a condition is true {
execute a block of code
}

Otherwise if it's false {
execute a different block of code
}

  • To make this type of selection we use an if...else statement
Syntax:

if (test)
{
    statements1;
} else {
    statements2;
}

Where:
test: the test condition to evaluate
statementsX: the statements to execute depending on the test





  • For example:
if (7 == guess) {
System.out.println("*** Correct! ***");
} else {
System.out.println("Sorry, that is not correct.");
System.out.println("Try again.");
}

  • ****Note that there is no test condition for the else clause****
  • The decision about which set of statements to use depends on only one condition
  • Note that you could write an if-else as a pair of complementary if statements instead, like:

if (7 == guess) {
System.out.println("*** Correct! ***");
}
if (7 != guess){
System.out.println("Sorry, that is not correct.");
System.out.println("Try again.");
}

  • However, it is easier and clearer to write an if-else statement instead
  • For clarity, write the if and else parts on different lines than the other statements
  • Also, indent the other statements
  • You can see an example of an if-else statement in the following example
Example Program With an if-else Statement

public class Guess{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int guess;
System.out.println("I'm thinking of a number between 1 and 10.");
System.out.println("Can you guess it?\n");
System.out.print("Enter your guess: ");
guess = input.nextInt();
if (7 == guess) {
System.out.println("*** Correct! ***");
} else {
System.out.println("Sorry, that is not correct.");
System.out.println("Try again.");
}
input.close();
}  //end of main
} //end of class

Formatting the if Statement and the else Statement

  • It is important to format the if statement professionally:

if (7 == guess) {
System.out.println("*** Correct! ***");
} else {
System.out.println("Sorry, that is not correct.");
System.out.println("Try again.");
}

  • Note how the conditional code is indented inside both the if and else portions
  • This lets us easily see which code is conditional and which is not
  • Also note the placement of curly braces
  • Different groups have different practices for placing curly braces for placing curly braces of if and if-else statements
  • In practice, you should use the style dictated by your group's policy
  • Or your professor's instructions

Activity 6.2: Is Your Number Even or Odd? (10pts)

  • Open up your program from the prior activity: Is Your Number Even?
  • Now add an else clause to display when the number is odd.
  • Update your program to display both options (even and odd).
  • Your program should work identically to the sample output below (except the use may enter different numbers)
  • Pay careful attention to line spacing and the use of "" around the words even and odd.
  • Once your program is working properly, submit it to Canvas.
Sample Output:

Welcome!
Enter a number and I will report back "even" or "odd."

Enter a whole number: 5
5 is odd.


Alternately:

Welcome!
Enter a number and I will report back "even" or "odd."

Enter a whole number: 10
10 is even.


5. Comparing Characters

  • Character data can be evaluated using the relational operators as well.
  • Because characters are primitive types, we can use the 6 relational operators (==, !=, <, >, <=, >=) to compare them.
  • Comparing characters works because Java stores characters as numbers using their Unicode values.
Unicode table

  • Note that letters nearer to the start of the alphabet have lower numerical Unicode values.
  • Thus a numerical comparison can decide the alphabetical order of characters.

Example Program Comparing Characters

1
2
3
4
5
6
7
8
9

public static void main(String[] args) {
    
    System.out.println("'A' < 'B': " + ('A' < 'B')); System.out.println("'A' > 'B': " + ('A' > 'B')); System.out.println("'A' <= 'Z': " + ('A' <= 'Z')); System.out.println("'X' >= 'Y': " + ('X' >= 'Y')); System.out.println("'X' == 'X': " + ('X' == 'X')); System.out.println("'X' != 'X': " + ('X' != 'X')); }

Wrap Up

  • Write a System.out.println statement to print the following message to the console:  "Make"<tab>"Model"<Tab>"Year"<New Line>
  • Given the following lines of code:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
  • Write an if statement to check if the the length of a String called name is equal to 0.
    • If so, print out an error message that says "Your name cannot be 0 characters long!"
  • With a partner, identify and correct the 3 mistakes in the code below:

    char choice = 'n';

    if (choice = y) {
          System.out.println(“Yes!”);
    } else (choice != y) {
         System.out.println(“No!”);
    }
f

Upcoming Assignments

  • Activity 6.1 and 6.2 due Thursday at 11:59pm
  • Assignment 5 due Friday at 11:59pm
  • Quiz 3 due Friday at 11:59pm
  • Assignment 6 due Tuesday at 11:59pm

~Have a Great Weekend!~