4: User Input

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

Which of the following statements is false?

  1. A literal string is enclosed in double quotes.
  2. The + operator is used to join, or concatenate, two strings to make one longer string.
  3. To include a double quote inside a string, you must put an escape character in front of it.
  4. Strings are stored in either 4 or 8 bytes, depending on the precision you want.

4.1: Interactive Keyboard Input

Objectives

At the end of the lesson the student will be able to:

  • Get user input from the command line
  • Get numbers from the command line

4.1.1: About Keyboard Input

  • For programs used infrequently, convenient to compile data into the code
  • For instance, to calculate the average of four numbers:
public class AverageOf4 {
    public static void main(String[] args) {
        double average = (32.6 + 55.2 + 67.9 + 48.6) / 4;
        System.out.println("Average = " + average);
    }
}
  • Easy to include the four numbers with the code operating on those numbers
  • However, you must recompile the program if you change any number
  • More convenient for users to enter data without recompiling a program
  • This section discusses how you can get user input while a program is running

4.1.2: Importing Classes

About Classes and Packages

  • To make it easier to write programs, Java has many libraries
  • These libraries contain prewritten code
  • Referred to as the Java Application Programming Interface (API)
  • Recall that all Java code is stored in classes
  • Groups of related classes are organized into packages

Some Commonly Used Packages

Package Name Description
java.lang Provides classes fundamental to Java.
java.io Provides classes to read and write files.
java.txt Provides classes to handle text, dates, and numbers
java.util Provides classes to work with collections and miscellaneous utilities.
javax.swing Provides classes to create graphical user interfaces and applets.

Importing Classes and Packages

  • Classes in the java.lang package are available automatically
  • To use other classes, you must import them
  • import packagename.ClassName;
        or
    import packagename.*;
    
  • Using the '*' wildcard will import all classes in a package
  • For example:
  • import java.text.NumberFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JFrame;
    import javax.swing.*;
    

4.1.3: Using System.in

  • System.in is the foundation object for entering data into a program
  • Recall that System.out is used to send data to the standard output stream
    • Usually the video display screen
  • Similarly, System.in is used to get data from the standard input stream
    • Usually the keyboard
    Scanner reader = Scanner.create(System.in);
    int n = reader.nextInt();
    

  • Streams deliver data as a stream of individual data bytes to the program
  • Java uses a number of objects to manage the streams of data
  • To use the stream objects, we need to import the java.io package:
  • import java.io.*;
  • System.in is an InputStream object that has basic read methods
  • Processes the input data by accepting one or more bytes at a time
    • Each byte is processed as an int
    • Allows using -1 as an end-of-file (EOF) marker
  • Use an InputStreamReader to convert int values of InputStream to char values
  • To program this, we "wrap" an InputStreamReader around System.in
  • InputStreamReader isr = new InputStreamReader(System.in);
    
  • Although we can now work with the char data types, easier to use strings
  • Class BufferedReader provides a method to read one line at a time
  • To program this, we "wrap" a BufferedReader around our InputStreamReader
  • BufferedReader br = new BufferedReader(isr);
    
  • Can now use the readLine() method to read one line at a time
  • String data = br.readLine();
    
  • Method readLine() collects all the input until the Enter key is pressed
  • Putting everything together into one program, we have:
import java.io.*;

public class LineInput {
    public static void main(String[] args) throws IOException {
        // set up for basic input stream
        InputStreamReader isr = new InputStreamReader(System.in);
        // need to use readLine()
        BufferedReader br = new BufferedReader(isr);

        System.out.print("Type a line and press Enter: ");
        String data = br.readLine();
        System.out.println("You entered: " + data);
    }
}
  • Note that we added a line of code after the main() method header
  • throws IOException
    
  • This code is required at this point for us to use the readLine() method
    • Will review the reason later in this lesson

4.1.4: Reading Numbers

  • Method readLine() accepts input from the user as strings
  • Often need to convert String values to numeric types
  • Recall that Java provides some very handy String conversion methods
  • We can use these methods to convert our string input into numbers

Conversion to Primitive Values

Return
Type
Conversion Method Example
int Integer.parseInt(String) Integer.parseInt("1234")
long Long.parseLong(String) Long.parseLong("123456")
float Float.parseFloat(String) Float.parseFloat("123.45")
double Double.parseDouble(String) Double.parseDouble("123.45")

An Example

  • Consider an application to sum (add) two numbers
import java.io.*;

public class SumOf2 {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr =
            new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);

        System.out.print("First number: ");
        String data = br.readLine();
        double num1 = Double.parseDouble(data);

        System.out.print("Second number: ");
        data = br.readLine();
        double num2 = Double.parseDouble(data);

        System.out.println(num1 + " + " + num2
            + " = " + (num1 + num2));
    }
}
  • We setup for reading from the command line as usual
  • InputStreamReader isr =
        new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    
  • We read each number as a string
  • System.out.print("First number: ");
    data = br.readLine();
    
  • Final step is to convert the String to a double
  • num1 = Double.parseDouble(data);
    
  • Then we can use the numbers using arithmetic operators
  • System.out.println("" + num1 + " + " + num2
        + " = " + (num1 + num2));
    

4.1.5: Summary

  • To make it easier to write programs, Java has many libraries of prewritten code
  • You can make use of this code by importing packages
  • import packagename.ClassName;
        or
    import packagename.*;
    
  • Alternatively, you can use the fully qualified package name
  • You can use System.in to read data from the command line
  • To use System.in, you need to need to import the java.io.IOException class
  • To convert bytes to chars, you wrap System.in in an InputStreamReader
  • To buffer the input and use the readLine() method, you also wrap the stream in a BufferedReader
  • Thus most code to read from the command line starts like:
  • import java.io.*;
    
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
    ...
    }
    
  • To read a string from the command line, you use the readLine() method
  • String input = br.readLine();
  • If you need a number as an input, you convert the String to a number

Exercise 4.1

  1. Start a text file named exercise4.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Use the following program for this exercise:
  4. import java.io.*;
    
    public class SumOf2 {
        public static void main(String[] args) throws IOException {
            InputStreamReader isr =
                new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
    
            System.out.print("First number: ");
            String data = br.readLine();
            double num1 = Double.parseDouble(data);
    
            System.out.print("Second number: ");
            data = br.readLine();
            double num2 = Double.parseDouble(data);
    
            System.out.println(num1 + " + " + num2
                + " = " + (num1 + num2));
        }
    }
  5. Record the answers to the following questions in your exercise4.txt file:
  1. Enter and execute the above program.
  2. Enter the phrase "bad data" at an input prompt.
  3. Q1: What error message did you see?

  4. Remove the code throws IOException and recompile the program.
  5. Q2: What error message did the compiler give you?

4.2: Using Dialogs for User I/O

Objectives

At the end of the lesson the student will be able to:

  • Collect user input in an input dialog box
  • Show messages using a message dialog

4.2.1: Introduction to Dialogs

  • Java provides GUI methods for user input and output
  • Use the JOptionPane() class
  • Static Method Description
    showConfirmDialog Asks a confirming question, like yes/no/cancel.
    showInputDialog Prompts for user text input.
    showMessageDialog Tell the user about something that has happened.

  • An input dialog will display a window similar to the following:
  • Syntax for the simplest form of the method is like:
  • String variable = JOptionPane.showInputDialog(String)
    
  • Argument String is a prompt displayed within the input dialog box
  • For example, the following statement produces the input dialog shown
  • String inputString = JOptionPane.showInputDialog(
        "Enter your first name:");
    
  • After the dialog is displayed, the program scans keyboard for input
  • As the user enters data, the dialog box displays the characters
  • Method showInputDialog returns a String data type containing user input
  • Need to save this data in a variable for processing

4.2.2: Coding Dialogs

  • Lets create a simple program to ask for and display a name
    • Adapted from textbook page 65
  • We use all three dialog boxes:
    1. showInputDialog: ask for name
    2. showConfirmDialog: verify entry
    3. showMessageDialog: display results
  • Complete program shown below:
import javax.swing.JOptionPane;

public class NameApp {
    public static void main(String[] args) {
        String inputString = JOptionPane.showInputDialog(
            "Enter your first name: ");
        int choice = JOptionPane.showConfirmDialog(null,
            "Are you sure?");
        String message = "First name: " + inputString + "\n"
                         + "Choice: " + choice + "\n"
                         + "Press enter to exit.";
        JOptionPane.showMessageDialog(null, message);
        System.exit(0);
    }
}

Input with showInputDialog()

  • Use the showInputDialog method of JOptionPane to get text input from users
  • In the above example, we created the first dialog like this:
  • String inputString = JOptionPane.showInputDialog(
        "Enter your first name:");
    
  • Essentially a single line of code

Input with showConfirmDialog()

  • Use the showConfirmDialog method of JOptionPane to get text input from users
  • In the above example, we created the first dialog like this:
  • JOptionPane.showConfirmDialog(null, "Are you sure?");
    

Output with showMessageDialog()

  • Use the showMessageDialog to show the user a message
  • From the above example:
  • String message = "First name: " + inputString + "\n\n"
                     + "Press enter to exit.";
    JOptionPane.showMessageDialog(null, message);
    
  • Note that you can use both showInputDialog() and showConfirmDialog() for output as well

4.2.3: Exiting with System.exit()

  • When a GUI is used, a thread is started
  • To terminate this thread and allow the program to end, you use System.exit
  • Otherwise, the user must use Ctrl+C keys to exit the program
  • System.exit(0);
  • Passing the number 0 to the exit() method means that the program exited normally.
  • You must call System.exit(0) when using GUIs for your program to exit correctly

4.2.4: Enhancing Dialogs

Commonly-Used Arguments in JOptionPane Methods

Argument Description
parentComponent An object representing the frame of the dialog box and controls its placement on the screen. If null is used, the dialog is centered on the screen.
messageString A descriptive message displayed in the dialog box.
titleString A title typically placed in the title bar above the dialog box.
messageTypeInt Indicates the type of icon to display in the dialog box. Use one of the fields of JOptionPane to choose the icon.

Examples of Other Methods for Displaying Dialog Boxes

  • showInputDialog can accept four arguments
  • JOptionPane.showInputDialog(parentComponent, messageString,
            titleString, messageTypeInt);
    
  • To display a different dialog without an input field:
  • JOptionPane.showMessageDialog(parent, message);
    
  • If the parent component is unknown, you can use null for that argument
  • JOptionPane.showMessageDialog(null, "Hello, world!");
    

Icons provided by JOptionPane

  • One can include the following icons (or not) in the dialogs

Icon Message Type Description
JOptionPane.ERROR_MESSAGE Displays an error icon.
JOptionPane.INFORMATION_MESSAGE Displays an information icon.
JOptionPane.WARNING_MESSAGE Displays an warning icon.
JOptionPane.QUESTION_MESSAGE Displays an question icon.
  JOptionPane.PLAIN_MESSAGE Does not display an icon.

Further Information

4.2.5: Summary

  • JOptionPane class provides several methods to display GUI dialogs
  • Must import the JOptionPane class to use these methods
  • import javax.swing.JOptionPane;
  • JOptionPane has three commonly-used methods for dialog boxes
  • Static Method Description
    showConfirmDialog Asks a confirming question, like yes/no/cancel.
    showInputDialog Prompts for user text input.
    showMessageDialog Tell the user about something that has happened.

  • You can enhance dialogs with titles and icons
  • Must use the System.exit() method to end programs that use GUIs

Exercise 4.2

Modify and rename your program from Exercise 3.3 to use dialogs rather than the command line. Collect user input using showInputDialog() and display the results using showMessageDialog(). Save your modified program along with this weeks exercises.

4.3: Problem Solving and Pair Programming

Objectives

At the end of the lesson the student will be able to:

  • Describe the purpose of programming
  • Create simple algorithms
  • Discuss the pros and cons of pair programming

4.3.1: Problems and Problem-Solving

  • Recall that programming is about solving problems using a computer program
  • When you first start computer programming, you may think that the hard part is translating your ideas into code
  • This is definitely not the case
  • The most difficult part is finding a solution to the problem
  • After finding a solution, translating your solution to code is a routine, almost mechanical, task

Defining a Problem

  • You first start solving a problem by understanding its requirements
  • Understanding the requirements often includes analysis of:
    1. Data inputs: files, user interaction
    2. Data manipulation of data: computations, selection
    3. Data output: output device, formats
  • If the problem is complex, you divide it into sub-problems
  • Each sub-problem is then analyzed to understand its requirements
  • At the end, you should write (or type) a definition of the problem, or sub-problems, in your own words

4.3.2: Algorithms

  • After you define a problem, you write out a sequence of steps to solve the problem
  • These steps should be written in a natural language such as English or Español
  • Instructions like these are referred to as an algorithm
  • Algorithm -- a sequence of instructions to solve a problem.

Total cost of Items

Problem: Total the cost for a list of items.

Algorithm:

  1. Write the number 0 on a blackboard (or other media)
  2. Do the following for each item on the list:
    • Add the cost of the item to the number on the board
    • Replace the old number by this sum
  3. Announce that the answer is the number written on the board

Play Tic-Tac-Toe

Problem: Play the game of tic-tac-toe.

Algorithm:

  1. Select 2 players
  2. Draw a big #
  3. Player 1: draw an X in one of the squares
  4. Player 2: draws an O in some square
  5. Continue alternating between the players until either:
    • Someone has three letters in a row or diagonal
    • All the squares are filled.

Observations about Algorithms

  • Notice that the sequence of steps you follow in a algorithm is often important
  • Also, notice that algorithms often require making one or more decisions
  • In addition, algorithms often contain repetition: steps that are repeated

4.3.3: Pair Programming

  • Defining problems and developing algorithms on your own is often difficult
  • You may work with others, though it is best to try to define a problem and develop an algorithm on your own first
  • What you cannot do is show other people your homework solutions or code
  • However, when you translate the algorithms into code, you often run into syntax errors that are difficult to see
  • It would be nice to get help from another human in these cases
  • However, the instructor prohibits asking most people from looking at your code
  • What is the solution to this problem?
  • Pair Programming for Homework Assignments

Defining Pair Programming

  • Pair programming is two people work together on one computer at the same time
    • Exactly two people: not one nor three or more
    • Exactly one computer: not two or more
  • The driver operates the keyboard and mouse
  • The navigator actively participates in the programming
    • Analyzes the design and code to prevent errors
    • Also in charge of using printed reference materials like textbooks
  • Each person "drives" about half the time
    • Physically get up and move positions when switching roles
  • At most 25% of your time is spent working alone
    • Any work done alone is reviewed by the other person
  • The object is to work together and to learn from each other
  • You cannot divide the work into two pieces with each partner working on a separate piece

Why Pair Program?

  • Students who pair program report:
    • Higher confidence in a program solution
    • More satisfaction with programming
  • Instructors report higher retention rates

More Information

4.3.4: Best Practices

  • You may choose any other student in this class for a partner
  • Both of your names appear on the assignment
  • When choosing partners and working together, certain practices help you perform better
  • Pair-programmers are more successful when they have similar experience levels
  • Need to find a partner with whom you can easily exchange ideas

Getting Along

More Information

4.3.5: Summary

  • Programming is about solving problems using a computer program
  • To develop a computer program, you start by defining the problem(s) to solve
  • Once a problem is well defined, you develop an algorithm to solve it
  • An algorithm is a sequence of instructions to solve a problem
  • Since defining problems, developing algorithms and implementing algorithms is hard, you can work with a partner
  • Use some care when choosing a pair-programming partner to maximize your sucess
  • In addition, both you and your partner should read: All I Really Need to Know about Pair Programming I Learned In Kindergarten

Exercise 4.3

  1. Label this exercise: Exercise 4.3
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in your exercise4.txt file.

Specifications

  1. We will count off and divide into separate groups
  2. Within your group, exchange email addresses so that you can send the answer to this exercise to each other.
  3. As a group, take 10 minutes to define the problem and describe an algorithm for getting from this classroom to Watsonville

4.4: Relationships, Logic and Truth

Objectives

At the end of the lesson the student will be able to:

  • Use relational expressions to produce boolean values
  • Use logical operators to code complex conditions

4.4.1: The Value of a Relationship

  • In addition to arithmetical operations, all computers can compare numbers
  • Many decisions can be reduced to choosing between two numbers
  • Comparing numbers can make computers seem "intelligent"
  • Expressions that compare operands are called relational expressions
    • Also called conditions
  • Simple relational expressions have one relational operator comparing two values
  • relational expression

  • A relational expression always evaluates to either true or false
  • The relational operators are:
  • Math Name Java Example Result
    = Equal to == 5 == 10
    2 == 2
    false
    true
    Not equal to != 5 != 10
    2 != 2
    true
    false
    < 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
    > 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

  • You may use relational operators with integer, floating-point and character data

4.4.2: Comparing Characters

  • Character data can be evaluated using relational operators
  • For these comparisons, char values are automatically coerced to int values
  • Letters nearer to the start of the alphabet have lower numerical values
  • Thus a numerical comparison can decide the alphabetical order of characters
  • For example:
  • Expression Result
    'A' > 'C' false
    'D' <= 'Z' true
    'E' == 'F' false
    'G' >= 'M' false
    'B' != 'C' true

4.4.3: Logical Operators

  • Sometimes you want to consider several relational expressions at once
  • Logical operators allow you to consider multiple cases and to change conditions
  • Use ! operator to reverse value of expression
  • Use && to AND two or more conditions
  • Use || to OR two or more conditions
  • ! Operator
    If expr is... Then ! expr is... Example Result
    true false !true false
    false true !(5 < 2) true

  • && operator returns true only if expressions on both sides are true
  • && Operator
    If expr1 is... And expr2 is... Then expr1 && expr2 is... Example Result
    true true true 5 < 10 && 5 > 2 true
    true false false 5 < 10 && 5 < 2 false
    false true false 5 > 10 && 5 > 2 false
    false false false 5 > 10 && 5 < 2 false

  • || operator returns true if either expression is true
  • || Operator
    If expr1 is... || expr2 is... Then expr1 || expr2 is... Example Result
    true true true 5 < 10 || 5 > 2 true
    true false true 5 < 10 || 5 < 2 true
    false true true 5 > 10 || 5 > 2 true
    false false false 5 > 10 || 5 < 2 false

Common Mistake with Logical Expressions

Logical expressions often read like "normal" English. However, Java syntax requires more detail. For example we might say in English: A equals B or C, but the corresponding boolean expression is A == B || A == C

4.4.4: What is Truth?

  • "What is truth?" may seem more appropriate for philosophy than programming
  • However, in programming we have to decide this question often
  • As we saw, computers evaluate conditions to either true or false.
  • To get a computer to make a decision, we have to reduce questions to either true or false
  • We will explore computer decision making in the next section

4.4.5: Summary

  • Many decisions can be reduced to choosing between two numbers
  • Comparing numbers can make computers seem "intelligent"
  • Relational expressions include:
  • ==  !=  <   <=  >   >=
  • Similarly, you can compare letters since letters are stored as numbers
    • Used to alphabetize letters and words in a computer program
  • Relational expressions always evaluate to either true or false
  • When you need to compare several conditions, you use logical operators
  • !   &&  ||
  • For example:
  • 5 > 10 || 5 > 2

Exercise 4.4

With a partner, if needed, take 10 minutes to complete the following:

  1. Start a text file named exercise4.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 4.4
  4. Submit all exercises for this lesson in one file unless instructed otherwise

Specifications

For the values:

int a = 5, b = 2, c = 4, d = 6;

Record the value of each of the following relational expressions in your exercise4.txt file.

  1. a > b
  2. a != b
  3. d % b == c % b
  4. a * c != d * b
  5. b % c * a != a * b

As a final part of this exercise, run the following program and answer these questions:

  1. Given that the variables a and b have already been declared and assigned values, write an expression that evaluates to true if a is greater than or equal to zero and b is negative
  2. Given that the variables a and b have already been declared and assigned values, write an expression that evaluates to true if a is positive (including zero) or b is negative (excluding zero).
  3. Given the boolean variable isValid has already been declared and assigned a value of either true or false, write an assignment statement that reverses (toggles) the value.
public class TruthTable {
    public static void main(String[] args) {
        boolean p, q;

        System.out.println("p\tq\t!p\tp && q\tp || q");
        System.out.println("-\t-\t--\t------\t------");

        p = true;
        q = true;
        System.out.print(p + "\t" + q + "\t" + !p);
        System.out.println("\t" + (p && q) + "\t" + (p || q));

        p = true;
        q = false;
        System.out.print(p + "\t" + q + "\t" + !p);
        System.out.println("\t" + (p && q) + "\t" + (p || q));

        p = false;
        q = true;
        System.out.print(p + "\t" + q + "\t" + !p);
        System.out.println("\t" + (p && q) + "\t" + (p || q));

        p = false;
        q = false;
        System.out.print(p + "\t" + q + "\t" + !p);
        System.out.println("\t" + (p && q) + "\t" + (p || q));
    }
}

4.5: Selection Statements

Objectives

At the end of the lesson the student will be able to:

  • Choose appropriate selection statements
  • Code selection statements

4.5.1: Flow Of Control

  • Term flow 0f control refers to the order a program executes instructions
  • All programs can be written with three control flow elements:
  1. Sequence - continue with the next instruction
    • Sequence is the default operation
  2. Selection - a choice between at least two options
    1. Either execute some instruction based on a condition
    2. Or continue with the next instruction
    3. if
      if-else
      if-else if-else if- ... -else
      
  3. Repetition - a loop (repeat a block of code)
    At the end of the loop:
    • Either go back and repeat the block of code
    • Or continue with the next instruction after the block
    • while
      
  • We will start with selection statements

4.5.2: Using if Statements

  • Simplest selection statement is an if statement
  • Executes a section of code only if a condition is true
  • if (condition) {
       // execute statements only if true
    }
    
  • If the condition is not true, the computer skips the code
  • The condition can be a relational or logical expression
  • For clarity, write the if on a different line than the statements
  • Also, indent the statements that are executed

For Example

  • What do you notice about the following code?
import javax.swing.JOptionPane;

public class GuessingGame {
    public static void main(String[] args) {
        int guess = 0;
        String input = "";
        String output = "";

        String msg = "I'm thinking of a number between"
                     + " 1 and 10.\nCan you guess it?";
        input = JOptionPane.showInputDialog(msg);
        guess = Integer.parseInt(input);

        if (guess == 7) {
            output = "*** Correct! ***";
            JOptionPane.showMessageDialog(null, output);
        }

        System.exit(0);
    }
}

About those Curly Braces

  • Technically, the if statement affects only the single statement that follows
  • We use curly braces to make the following statement into a block
  • This allows us to put any number of statements within the block
  • Though curly braces are not always required, the best practice is to include them

4.5.3: Using if-else Statements

  • Statement if-else expands the selection statement
  • If a condition is true
    • then do this
  • otherwise it is false
    • so do something else
  • General syntax:
  • if (condition) {
        statement1;
    } else {
        statement2;
    }
    
  • For clarity, if and else are written on different lines than the statements
  • Also, the statements are indented

For Example

  • What do you notice about the following code?
import javax.swing.JOptionPane;

public class GuessingGame2 {
    public static void main(String[] args) {
        int guess = 0;
        String input = "";
        String output = "";

        String msg = "I'm thinking of a number between"
                     + " 1 and 10.\nCan you guess it?";
        input = JOptionPane.showInputDialog(msg);
        guess = Integer.parseInt(input);

        if (guess == 7) {
            output = "*** Correct! ***";
        } else {
            output = "Sorry, that is not correct.";
        }
        JOptionPane.showMessageDialog(null, output);

        System.exit(0);
    }
}

Programming Style: Placement of Braces

  • Different practices for placing curly braces in a compound statement
  • Many programmers prefer placing curly braces on separate lines
  • However, Java standard is to place the opening brace on the same line as shown above
  • In practice, you should use the style dictated by your company's policy
    • Or your professor's instructions
  • For the acceptable styles for this course see: Curly Braces

4.5.4: Nested if Statements

  • You can include if statements within other if statements
  • Each inner if statement is evaluated only if outer condition is met

For Example

  • What do you notice about the following code?
import javax.swing.JOptionPane;

public class TempGuide {
    public static void main(String[] args) {
        String msg = "Enter a temperature";
        String input = JOptionPane.showInputDialog(msg);
        double temp = Double.parseDouble(input);

        String output;
        if (temp > 65) {
            if (temp > 75) {
                output = "That's too hot!";
            } else {
                output = "That's just right.";
            }
        } else {
            output = "That's cold!";
        }
        JOptionPane.showMessageDialog(null, output);
        System.exit(0);
    }
}

  • Nested conditionals can be confusing if too deep
  • Rule of thumb: no more than three deep

"Dangling Else" Problem

  • Potential problem with nested if statements is the dangling else problem
  • if (condition1)
        if (condition2)
            Statement1;
    else
        Statement2;
    
  • Indentation is misleading and should be:
  • if (condition1)
        if (condition2)
            Statement1;
        else
            Statement2;
    
  • Common mistake is not matching else with the correct if
  • Rule: else always matches the last unmatched if
  • Avoid this problem by using curly braces to specify the grouping
  • if (condition1) {
        if (condition2) {
            Statement1;
        } else {
            Statement2;
        }
    }
    

4.5.5: Using if-else Chains

  • Often confusing when if statements are nested within other if statements
    • Should avoid this type of construction
  • However, a very useful construction is an if ... else if statement
    • An if statement is nested inside an else statement
  • Tests conditions sequentially until the first true condition is found
  • The first true condition executes the code within the block
    • Skips the remainder of the if-else chain
  • Often used to create a menu

For Example

  • What do you notice about the following code?
import javax.swing.JOptionPane;

public class TempGuide2 {
    public static void main(String[] args) {
        String msg = "Enter a temperature";
        String input = JOptionPane.showInputDialog(msg);
        double temp = Double.parseDouble(input);

        String output;
        if (temp > 75) {        // first condition
            output = "That's too hot!";
        } else if (temp > 65) { // second condition
            output = "That's just right.";
        } else {                // default condition
            output = "That's cold!";
        }
        JOptionPane.showMessageDialog(null, output);
        System.exit(0);
    }
}

  • Note the arrangement of if-else statements

4.5.6: Testing Multiple Conditions

  • With logical operators (&&, ||, !), you can test for multiple conditions
  • For example, you can create condition that displays only if two conditions are true
  • What do you notice about the following code?
import javax.swing.JOptionPane;

public class TempGuide3 {
    public static void main(String[] args) {
        String msg = "Enter a temperature";
        String input = JOptionPane.showInputDialog(msg);
        double temp = Double.parseDouble(input);

        String output;
        if (temp >= 65 && temp <= 75) {
            output = "That's just right.";
        } else {
            output = "That's uncomfortable!";
        }
        JOptionPane.showMessageDialog(null, output);
        System.exit(0);
    }
}

  • How could we get the same result using a logical OR operation?

4.5.7: Summary

  • Selection is a choice between at least two options
  • Selection statements include:
  • if
    if-else
    if-else if-else if- ... - else
    
  • Single statements are expanded into compound statements using blocks
  • Nested if statements are legal but often confusing
    • Which if does an else match up with?
    • Use curly braces to clarify
    • Better yet, avoid using nested if statements
  • In contrast, chains of if-else statements are very useful
    • Programs execute the code when the first condition matches
    • Often used to create menus

Exercise 4.5

  1. Label this exercise: Exercise 4.5
  2. Complete the following and record the answer to any questions in your exercise4.txt file.

Specifications

A student's letter grade is calculated according to the following table:

Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F

  1. Write a program that accepts a students numerical grade, converts the grade to an equivalent letter grade, and displays the letter grade.
  2. Q1: How do you make sure that only one condition is selected?

    Q2: How do you avoid the dangling-else problem?

  3. Submit your final program along with your exercise4.txt file.

You can use the following code to get started.

import javax.swing.JOptionPane;

public class GradeConverter {
    public static void main(String[] args) {
        String msg = "Enter a score";
        String input = JOptionPane.showInputDialog(msg);
        double score = Double.parseDouble(input);

        String output = "";
        // Insert statements here

        JOptionPane.showMessageDialog(null, output);
        System.exit(0);
    }
}

Wrap Up

    Reminders

    Due Next Class: A3: Conversions (9/27/04)
    Exercise 4 and CodeLab Lesson 4 (9/27/04)

  • When class is over, please shut down your computer
  • You may complete unfinished exercises at the end of the class or at any time before the next class.
  • Instructions on submitting exercises are available from the HowTo's page.

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: September 20 2004 @12:22:37