34
Java Programming, Java Programming, Second Edition Second Edition Chapter Five Chapter Five Input and Selection Input and Selection

Java Programming, Second Edition Chapter Five Input and Selection

Embed Size (px)

Citation preview

Page 1: Java Programming, Second Edition Chapter Five Input and Selection

Java Programming, Java Programming, Second EditionSecond Edition

Chapter FiveChapter Five

Input and SelectionInput and Selection

Page 2: Java Programming, Second Edition Chapter Five Input and Selection

In this chapter, you will:In this chapter, you will:

Accept keyboard inputAccept keyboard input Use the JOptionPane class for GUI input and outputUse the JOptionPane class for GUI input and output Draw flowchartsDraw flowcharts Make decisions with the if and if…else structuresMake decisions with the if and if…else structures Use compound statements in an if or if…else structureUse compound statements in an if or if…else structure Nest if and if…else statementsNest if and if…else statements Use AND and OR operatorsUse AND and OR operators Use the switch statementUse the switch statement Use the conditional and NOT operatorsUse the conditional and NOT operators Understand precedenceUnderstand precedence

Page 3: Java Programming, Second Edition Chapter Five Input and Selection

Accepting Keyboard InputAccepting Keyboard Input

Run timeRun time - When the program is executing - When the program is executing A program that accepts values at run time is A program that accepts values at run time is

interactiveinteractive because it exchanges communications because it exchanges communications with the userwith the user

Providing values during run time requires input, Providing values during run time requires input, usually through the keyboardusually through the keyboard

The The inin object has access to a method named read() object has access to a method named read() that retrieves data from the keyboard that retrieves data from the keyboard

Page 4: Java Programming, Second Edition Chapter Five Input and Selection
Page 5: Java Programming, Second Edition Chapter Five Input and Selection

Accepting Keyboard InputAccepting Keyboard Input

An An exceptionexception is an error situation is an error situation There are many different error situationsThere are many different error situations For example:For example:

Keyboard issuesKeyboard issuesThe user might enter the wrong data typeThe user might enter the wrong data type

Page 6: Java Programming, Second Edition Chapter Five Input and Selection

Accepting Keyboard InputAccepting Keyboard Input

Let the compiler handle the problem by Let the compiler handle the problem by throwing the exception, or passing the throwing the exception, or passing the error, to the operating systemerror, to the operating system Use Use throws Exceptionthrows Exception after the main() after the main()

method headermethod header

Page 7: Java Programming, Second Edition Chapter Five Input and Selection

Accepting Keyboard InputAccepting Keyboard Input

PromptPrompt- Message requesting user - Message requesting user inputinput For example:For example:

The string “Please enter a character”The string “Please enter a character”You are not required to supply a prompt but You are not required to supply a prompt but

it is helpful for the user if you do and the it is helpful for the user if you do and the user will be more likely to enter an user will be more likely to enter an appropriate responseappropriate response

Page 8: Java Programming, Second Edition Chapter Five Input and Selection

Using the JOptionPane Class for Using the JOptionPane Class for GUI Input and OutputGUI Input and Output

SwingSwing components- The classes found in the components- The classes found in the javax.swingjavax.swing package define GUI elements and package define GUI elements and provide alternatives to the provide alternatives to the System.in.read()System.in.read() and and System.out.println()System.out.println() methods methods

Swing classes are part of the Java Foundation Swing classes are part of the Java Foundation Classes, or JFCClasses, or JFC

To access the Swing components import the To access the Swing components import the javax.swing package using javax.swing package using javax.swing.*;javax.swing.*;

Page 9: Java Programming, Second Edition Chapter Five Input and Selection

Using the JOptionPane Class for Using the JOptionPane Class for GUI Input and OutputGUI Input and Output

JOptionPaneJOptionPane - Used to create standard - Used to create standard dialog boxesdialog boxes

Three standard dialog boxesThree standard dialog boxes InputDialogInputDialog - prompts the user for text input- prompts the user for text input MessageDialogMessageDialog - displays a user message- displays a user message ConfirmDialogConfirmDialog - asks the user a question, - asks the user a question,

with buttons for Yes, No, and Cancel with buttons for Yes, No, and Cancel responsesresponses

Page 10: Java Programming, Second Edition Chapter Five Input and Selection

Input Dialog BoxesInput Dialog Boxes

showInputDialog()showInputDialog() method- Creates method- Creates an input dialog boxan input dialog box Asks a question and uses a text field for Asks a question and uses a text field for

entering a responseentering a response Two componentsTwo components

The parent component The parent component The string component- contains a string or icon to The string component- contains a string or icon to

be displayedbe displayed

Page 11: Java Programming, Second Edition Chapter Five Input and Selection

Input Dialog BoxesInput Dialog Boxes

showInputDialog()showInputDialog() method with four method with four argumentsarguments

Parent componentParent component String component (prompt)String component (prompt) The title to be displayed in the title barThe title to be displayed in the title bar A class variable describing the type of dialog boxA class variable describing the type of dialog box For example:For example:

ERROR_MESSAGEERROR_MESSAGE INFORMATION_ MESSAGEINFORMATION_ MESSAGE QUESTION_MESSAGEQUESTION_MESSAGE

Page 12: Java Programming, Second Edition Chapter Five Input and Selection

Message Dialog BoxesMessage Dialog Boxes

Message Dialog Boxes- Uses a simple Message Dialog Boxes- Uses a simple window to display informationwindow to display information

Created with the Created with the showMessageDialog()showMessageDialog() methodmethod Parent componentParent component String componentString component

Page 13: Java Programming, Second Edition Chapter Five Input and Selection

Message Dialog BoxesMessage Dialog Boxes

showMessageDialog()showMessageDialog() method with four method with four argumentsarguments

Parent componentParent component String componentString component The title to be displayed in the title barThe title to be displayed in the title bar A class variable describing the type of dialog A class variable describing the type of dialog

boxbox For example:For example:

ERROR_MESSAGEERROR_MESSAGE INFORMATION_ MESSAGEINFORMATION_ MESSAGE QUESTION_MESSAGEQUESTION_MESSAGE

Page 14: Java Programming, Second Edition Chapter Five Input and Selection

Confirm Dialog BoxesConfirm Dialog Boxes

showConfirmDialog()showConfirmDialog() method- To method- To create a confirm dialog box which displays create a confirm dialog box which displays the options Yes, No, and Cancelthe options Yes, No, and Cancel

Page 15: Java Programming, Second Edition Chapter Five Input and Selection

Confirm Dialog BoxesConfirm Dialog Boxes

A confirm dialog box with 5 components:A confirm dialog box with 5 components: Parent componentParent component String componentString component The title to be displayed in the title barThe title to be displayed in the title bar An integer that indicates which option button will An integer that indicates which option button will

be shownbe shown An integer that describes the kind of dialog box An integer that describes the kind of dialog box

using the class variables ERROR_MESSAGE, using the class variables ERROR_MESSAGE, INFORMATION_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE, QUESTION_MESSAGE, or WARNING_MESSAGEWARNING_MESSAGE

Page 16: Java Programming, Second Edition Chapter Five Input and Selection

Drawing FlowchartsDrawing Flowcharts

Pseudocode- Programmers use a list of Pseudocode- Programmers use a list of tasks that must be accomplished to help tasks that must be accomplished to help them plan a program’s logicthem plan a program’s logic

Flowchart- The programmer writes the Flowchart- The programmer writes the steps in diagram form as a series of steps in diagram form as a series of shapes connected by arrowsshapes connected by arrows

Page 17: Java Programming, Second Edition Chapter Five Input and Selection

Making Decisions with the if and Making Decisions with the if and if…else Structuresif…else Structures

Making a decision involves choosing between Making a decision involves choosing between alternate courses of action based on some value alternate courses of action based on some value within a programwithin a program

The value the decision is based on is always The value the decision is based on is always Boolean-true or falseBoolean-true or false

You can use if or if…else statements to make a You can use if or if…else statements to make a decisiondecision

Page 18: Java Programming, Second Edition Chapter Five Input and Selection

if and if…else statementsif and if…else statements

Single alternative- You only perform an action Single alternative- You only perform an action based on one alternativebased on one alternative

Dual alternative- Requires two options for a Dual alternative- Requires two options for a course of actioncourse of action Provides the mechanism for performing one action Provides the mechanism for performing one action

when a Boolean expression evaluates as true and if it when a Boolean expression evaluates as true and if it evaluates to false a different action occurs evaluates to false a different action occurs

Page 19: Java Programming, Second Edition Chapter Five Input and Selection
Page 20: Java Programming, Second Edition Chapter Five Input and Selection
Page 21: Java Programming, Second Edition Chapter Five Input and Selection
Page 22: Java Programming, Second Edition Chapter Five Input and Selection

Using Compound Statements in an Using Compound Statements in an if or if…else Structureif or if…else Structure

To execute more than one statement that To execute more than one statement that depends on the evaluation of a Boolean depends on the evaluation of a Boolean expression, use a pair of curly braces to expression, use a pair of curly braces to place the dependent statements within a place the dependent statements within a blockblock

Page 23: Java Programming, Second Edition Chapter Five Input and Selection
Page 24: Java Programming, Second Edition Chapter Five Input and Selection

Nesting if and if…else Nesting if and if…else statementsstatements

Nesting if and if…else statements- Statements Nesting if and if…else statements- Statements with an if inside another ifwith an if inside another if

Nested if statements are useful when two Nested if statements are useful when two conditions must be met before some action can conditions must be met before some action can occuroccur

Page 25: Java Programming, Second Edition Chapter Five Input and Selection
Page 26: Java Programming, Second Edition Chapter Five Input and Selection
Page 27: Java Programming, Second Edition Chapter Five Input and Selection

Using AND and OR OperatorsUsing AND and OR Operators

AND operator- Used to determine whether AND operator- Used to determine whether two expressions are both truetwo expressions are both true Written as Written as &&&&

OR operator- Only one of two conditions is OR operator- Only one of two conditions is truetrue Written as Written as ||||

if (itemsSold > 3 && totalValue > 1000)if (itemsSold > 3 && totalValue > 1000)

bonus=50;bonus=50;

Page 28: Java Programming, Second Edition Chapter Five Input and Selection
Page 29: Java Programming, Second Edition Chapter Five Input and Selection

Using the Switch StatementUsing the Switch Statement

Switch statement- To test a single variable Switch statement- To test a single variable against a series of exact integer or character against a series of exact integer or character valuesvalues

The switch statement uses four keywordsThe switch statement uses four keywords switchswitch - starts the structure and is followed - starts the structure and is followed

immediately by a test expression enclosed in immediately by a test expression enclosed in parenthesesparentheses

casecase - is followed by one of the possible values for - is followed by one of the possible values for the test expression and a colonthe test expression and a colon

breakbreak - optionally terminates a switch structure at the - optionally terminates a switch structure at the end of each caseend of each case

default default - optionally is used prior to any action that - optionally is used prior to any action that should occur if the test variable does not match any should occur if the test variable does not match any casecase

Page 30: Java Programming, Second Edition Chapter Five Input and Selection
Page 31: Java Programming, Second Edition Chapter Five Input and Selection

Using the Conditional and NOT Using the Conditional and NOT OperatorsOperators

Conditional operator- Requires three Conditional operator- Requires three expressions separated with a question expressions separated with a question mark and a colonmark and a colon Is used as an abbreviated version of the if…Is used as an abbreviated version of the if…

else structureelse structure

(testExpression) ? true Result : false Result(testExpression) ? true Result : false Result

Page 32: Java Programming, Second Edition Chapter Five Input and Selection

Using the Conditional and NOT Using the Conditional and NOT OperatorsOperators

NOT operator- To negate the result of any NOT operator- To negate the result of any Boolean expressionBoolean expression Written as the exclamation point (!)Written as the exclamation point (!)

boolean oldEnough = (age > 25);boolean oldEnough = (age > 25);

if (!oldEnough)if (!oldEnough)

System.out.println(“Too young!”);System.out.println(“Too young!”);

Page 33: Java Programming, Second Edition Chapter Five Input and Selection

Understanding PrecedenceUnderstanding Precedence

Operations have higher and lower Operations have higher and lower precedencesprecedences

The order in which you use operators The order in which you use operators makes a differencemakes a difference

You can always use parentheses to You can always use parentheses to change precedence or make your change precedence or make your intentions clearintentions clear

Page 34: Java Programming, Second Edition Chapter Five Input and Selection