Welcome to Lesson 7!

Learning Objectives
By the end of today's class, you should know...
  • What is String concatenation
  • What is the String length method and how do you "call" it?
  • What is the String equals method and how do you "call" it?
  • What is the String toUpperCase method and how do you "call" it?
  • What is the String toLowerCase method and how do you "call" it?
  • What is the String charAt method and how do you "call" it?
  • How do you create decision points in your program using if statements?
  • How do you write programs where there are exactly two alternatives?

Announcements

  • Quiz 3 next class
    • Hand back Quiz 2
  • Midterm 2 next week!
  • Women in Computer Science Club Meeting tomorrow:
    • Attend Women in Tech Panel in Conference Rooms A & B from 12:30-1:30pm
    • Meet afterwards to discuss club leadership from 1:30-2:00pm


Review Activity

With a partner, answer the following questions:
  • Write a complete user interaction as follows (3-4 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
  • 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?

String Methods

  • Strings are a special type of variable called objects, which you will study in more detail in CIS 36B.
  • An object is a data type that can have methods associated with it
  • These methods are called member functions and are called using dot notation
  • The syntax for calling a member function of a String object is:
    StringName.methodName(arguments)
    
  • Where:
    • StringName: the name of the String variable
    • methodName: the name of the member function
    • arguments: the input values, if any
  • Once you create a String variable, you can call (use) its member functions

Some Commonly-Used String Methods

  • length(): Returns the number of characters in a String
    String str = "Hello";
    System.out.println("The number of characters is " + str.length());
  • equals(): Compares two Strings and tells you whether they are equal to each other (true) or not equal to each other (false).
         String cat1 = "Cat";
    String cat2 = "Kat";
    System.out.println("Cat equals Kat: " + cat1.equals(cat2));
    System.out.println("Car equals Car: " + "Car".equals("Car"));
  • toLowerCase() and toUpperCase(): Converts a String to all lower case characters or all upper case characters, respectively

    System.out.println("Capitalize".toUpperCase());
    System.out.println("LowerCase".toLowerCase());        
      

  • charAt: Returns a character at a specific index of the String.
    String greeting = "Hello, World!";
    char ohMy = greeting.charAt(4);
    System.out.println(ohMy);
    
  • The position numbers in a String start at 0. The last character is always one less than the length of the String
    Hello,
    World!
    0123456789101112
  • char w = greeting.charAt(7);
    Hello,
    World!
    0123456789101112

  • These are just some examples. There are many more things you can do with Strings!


Example Using String Methods

  • Consider the problem of extracting the initials from a person's name
  • What would be an algorithm for solving this problem?
  • To implement this algorithm, we can use the String method charAt()
  • The following program implements an algorithm for extracting the initials from a person's name


Activity 7.1: My Name Part 2 (10pts) 

  • Find a partner for pair programming.
  • Open up your MyName project from last class, and let's add to it.
  • Don't forget to include your partner's name in the comments at the top of the program.
  • Let's calculate the length of the user's first and last names and output the result to the console
System.out.println("The length of your first name is " + first_name.length() + " letters");
  • Now add a similar System.out.println statement to display the length of the user's last name AND full name (remember the full_name variable)
  • Next, let's return the user's initial's to them.
  • Let's declare a new String variable called initials that you place at the top of your program with the other variable declarations.
String initials;

  • Next, we are going to use the charAt() function to extract the initials from the user's first and last names.
  • A person's initials are composed of the first letters of their first and last names.
  • Therefore, we need the letters at position 0 in the first_name and last_name variables.
initials = "" + first_name.charAt(???) + ?????????;
  • Note that "" is called the empty String.
  • Next, print the results to the console to display for the user.
System.out.println("Your initials are: " + initials);
  • Let's compare their first and last names to see if they are the same using the equals method.
  • Add a statement like the following after the last System.out.println:

System.out.println("Your first and last name are the same: " + first_name.equals(last_name));

  • Finally, let's print out the full name in all upper case and all lower case. Add two System.out.println statements:

System.out.println("Your name in all capitals is: " + full_name.toUpperCase());

//Now add a similar statement to print out the name in all lower case characters

  • When you are finished, the output of your program should look like below.
  • However, look closely and you will see a mistake in my output below.
  • Please correct the mistake before you turn it in (there are a couple of different approaches you can take to this problem).
  • Submit your MyName.java program to Canvas.
  • Remember that both partners need to submit for full credit.

The output of your program should look like this (except user input will vary):

Hi! I want to learn your name.
Please enter your first name: Jennifer
Please enter your last name: Parrish
Nice to meet you Jennifer Parrish!
The length of your first name is 8 letters
The length of your last name is 7 letters
The length of your full name is 16 letters
Your initials are: JP
Your first name and last name are the same: false
Your name in all capitals is: JENNIFER PARRISH
Your name in all lower case letters is: jennifer parrish


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
    \"
     Double quote
     \' Single quote
     \t Tab
     \n New Line

  • We will practice with escape sequences in our homework.


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 not want to display an error message

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
  • 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

MathNameJava
Examples  ResultNotes
=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:

_images/flowchart_if_only.png

image source

  • You can see an example of an if statement in the following example

Example Program With an if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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! ***");     }     }

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 static void main(String[] args)
{
    int x = 3;
    if(x < 5)
    {
    System.out.println("x is less than 5!"); //NO!! need to indent twice b/c inside 2 sets of curly braces
    }
}


Correct curly braces:


public static void main(String[] args)
{
    int x = 3;
    if(x < 5)
    {
        System.out.println("x is less than 5!"); //Yes!! Indent twice b/c inside 2 sets of curly braces
    }
}

Group Activity: 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?
  • Let's write a program to test a number to determine whether it is even or odd.
  • Open up Eclipse and create a new project called Even
  • At the top of your program, add a block comment to contain your name, your partner's name and section information:
/*
* @author Name1
* @author Name2
* Section Info
*/

  • 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 add a Scanner variable to help us read the user input from the keyboard (System.in) later in the program:
Scanner in = new Scanner(System.in);
  • Next, let's 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 will tell you if it's even or odd!");
  • Run your program to verify it is working properly. If not, ask the instructor or another student for help.
  • Let's prompt the user to enter a whole number.
System.out.print("Please enter a whole number: ");
  • Next, we need to capture the user input and store it in the testNum variable. Complete the following statement and add it to your program:
testNum = ????;
  • Now, we will get a chance to try out 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?
  • Then, hold onto it. We will improve upon this program in the next activity.


Using if-else Statements

  • Sometimes we want to choose between two actions
  • If a condition is true
    • execute a block of code
  • Otherwise it is 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


C++ if...else statement

(from http://www.tutorialspoint.com/cplusplus/cpp_if_else_statement.htm)


  • 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 on 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.prinln("*** 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.");     } }

Formatting the if 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 7.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.
  • When your program is able to display both options (even and odd), submit it to Canvas.
  • Both partners need to submit for full credit.


Wrap Up
  • Answer the questions from today's learning objectives

Upcoming Assignments
  • Assignment 7 due Thursday at 1:20pm on Canvas
  • Lab 4 due Friday at midnight
  • Quiz 3 on Thursday
~See You Thursday!~