chapter 71© copyright janson industries 2014 avoiding data entry errors ▮ catching an exception...

76
Chapter 7 1 © copyright Janson Industries 2014 Avoiding Data Entry Errors Catching an Exception Formatters StringBuffer Choice Iteration Method Overloading Non-graded Assg

Upload: posy-carpenter

Post on 25-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 1© copyright Janson Industries 2014

Avoiding Data Entry Errors

▮ Catching an Exception

▮ Formatters

▮ StringBuffer

▮ Choice

▮ Iteration

▮ Method Overloading

Non-graded Assg

Page 2: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 2© copyright Janson Industries 2014

Lots of different types of errors:

Entering a qty of 1 and price of 1.50, results in cost =

$1.5975

Considered a Soft error (no exception)

Page 3: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 3© copyright Janson Industries 2014

Throwing Exceptions

▮ When a hard error is encountered, the JVM throws an exception

▮ Example: trying to divide by "four”

▮ The operating system does not react well…

Page 4: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 4© copyright Janson Industries 2014

Normally a user: Enters valid values Clicks the Divide button Result is displayed in the label

Page 5: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 5© copyright Janson Industries 2014

Entering the incorrect value “four” and clicking Divide does

not result in an exception being displayed on the

Frame...

... it's displayed in the console

Page 6: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 6© copyright Janson Industries 2014

Run Time Exceptions

Or worse yet, in production

Is this how the user should see an exception/error?

Page 7: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 7© copyright Janson Industries 2014

Throwing Exceptions

▮ To handle the error programmatically, program must catch the exception

▮ For example, dividing two user supplied values can result in an exception(s)

▮ Here’s the code for calculator example…

Page 8: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 © copyright Janson Industries 2014 8

Calculator Code

Various imports

Various variables

Page 9: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 9© copyright Janson Industries 2014

private Checkbox divCB = null;

private Button exitBtn = null;

private Button execBtn = null;

private Label resultLbl = null;

CheckboxGroup arithFunc = new CheckboxGroup();

private double result, firstNum, secondNum;public void windowActivated(WindowEvent e){}

public void windowClosed(WindowEvent e) {}

public void windowClosing(WindowEvent e) {

this.dispose();}

public void windowDeactivated(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowOpened(WindowEvent e) {}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == exitBtn)

{ System.exit(0);}

else

{this.doCalc();}}

public void itemStateChanged(ItemEvent e) {

this.doCalc();

}

WindowListener methods

Action Listener methodItem Listener

method

Make result, firstNum, and secondNum class level

variables

Page 10: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 10© copyright Janson Industries 2014

The workhorse

private void doCalc() {

String msgBegin = new String("The result of ");

String msgPrep = new String(" ");

firstNum = Double.valueOf(numeratorTF.getText());

secondNum = Double.valueOf(denominatorTF.getText());

if (addCB.getState()) {

msgBegin = msgBegin + "adding ";

msgPrep = msgPrep + "to ";

result = firstNum + secondNum;

} else {

if (subCB.getState()) {

msgBegin = msgBegin + "subtracting ";

msgPrep = msgPrep + "from ";

result = firstNum - secondNum;

} else {

msgPrep = msgPrep + "by ";

if (multCB.getState()) {

msgBegin = msgBegin + "multiplying ";

result = firstNum * secondNum;

} else {

Page 11: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 11© copyright Janson Industries 2014

if (divCB.getState()) {

msgBegin = msgBegin + "dividing ";

result = firstNum / secondNum;

}}}}

if (subCB.getState()) {

resultLbl.setText(msgBegin + secondNum + msgPrep + firstNum + " is " + result);

} else {

resultLbl.setText(msgBegin + firstNum + msgPrep + secondNum + " is " + result);

}

}

public static void main(String[] args) {

new Calculator();

}

public Calculator() {

super();

initialize();

}

main

Constructor

Page 12: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 © copyright Janson Industries 2014 12

Visual component objectsprivate Checkbox getAddBox() {

if (addBox == null) {

addBox = new Checkbox();

addBox.setLabel("Add");

addBox.setCheckboxGroup(arithFunc);

addBox.setBounds(new Rectangle(18, 101, 43, 23));

addBox.addItemListener(this);

}

return addBox;

}

private Checkbox getSubBox() {

if (subBox == null) {

subBox = new Checkbox();

subBox.setBounds(new Rectangle(75, 101, 66, 23));

subBox.setLabel("Subtract");

subBox.setCheckboxGroup(arithFunc);

subBox.addItemListener(this);

}

return subBox;

}

private Checkbox getMultBox() {

if (multBox == null) {

multBox = new Checkbox();

multBox.setBounds(new Rectangle(155,101, 59, 23));

multBox.setLabel("Multiply");

multBox.setCheckboxGroup(arithFunc);

multBox.addItemListener(this);

}

return multBox;

}

private Checkbox getDivBox() {

if (divBox == null) {

divBox = new Checkbox();

divBox.setBounds(new Rectangle(228, 101, 54, 23));

divBox.setLabel("Divide");

divBox.setCheckboxGroup(arithFunc);

divBox.addItemListener(this);

}

return divBox;

}

Page 13: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

© copyright Janson Industries 2014

private TextField getNumeratorTF() {

if (numeratorTF == null) {

numeratorTF = new TextField();

numeratorTF.setBounds(new Rectangle(196, 37, 36, 23));

}

return numeratorTF;

}

private TextField getDenominatorTF() {

if (denominatorTF == null) {

denominatorTF = new TextField();

denominatorTF.setBounds(new Rectangle(196, 69, 36, 23));

}

return denominatorTF;

}

private Button getExitBtn() {

if (exitBtn == null) {

exitBtn = new Button();

exitBtn.setLocation(new Point(240, 167));

exitBtn.setLabel("Exit");

exitBtn.setSize(new Dimension(50, 23));

exitBtn.addActionListener(this);

}

return exitBtn;

}

private Button getExecBtn() {

if (execBtn == null) {

execBtn = new Button();

execBtn.setLocation(new Point(125, 167));

execBtn.setLabel("Execute");

execBtn.setSize(new Dimension(50, 23));

execBtn.addActionListener(this);

}

return execBtn;

} Chapter 7 13

Visual component

objects

Page 14: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 14© copyright Janson Industries 2014

private void initialize() {

resultLbl = new Label();

resultLbl.setBounds(new Rectangle(12, 129, 278, 23));

resultLbl.setAlignment(Label.CENTER);

resultLbl.setText("");

denominatorLbl = new Label();

denominatorLbl.setBounds(new Rectangle(46, 69, 139, 23));

denominatorLbl.setText("Enter second number: ");

denominatorLbl.setAlignment(Label.RIGHT);

numeratorLbl = new Label();

numeratorLbl.setBounds(new Rectangle(74, 37, 111, 23));

numeratorLbl.setAlignment(Label.RIGHT);

numeratorLbl.setText("Enter first number: ");

this.setLayout(null);

this.setSize(300, 200);

this.setTitle("Frame");

this.addWindowListener(this);

this.add(numeratorLbl, null); this.add(denominatorLbl, null);

this.add(getNumeratorTF(), null); this.add(getDenominatorTF(), null);

this.add(getMultCB(), null); this.add(getAddCB(), null);

this.add(getSubCB(), null); this.add(getDivCB(), null);

this.add(getExitBtn(), null); this.add(getExecBtn(), null);

this.add(resultLbl, null); this.setVisible(true); }

}

initialize

Page 15: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 15© copyright Janson Industries 2014

Run Time Exceptions

▮ How do you identify statements that might generate exceptions?

▮ Try to cause errors through destructive testing

▮ Input bad data▮ Null value, wrong data type, incomplete value

▮Make resources unavailable▮ Delete an expected file, no Internet connection

Page 16: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 16© copyright Janson Industries 2014

Run Time Exceptions

▮ By typing in bad values like “four” and 0, exceptions are generated

▮ Stack trace messages will identify

▮ Line of code that caused the exception

▮ The particular exception that was generated

▮ Read through stack for message pertaining to your class

Page 17: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 17© copyright Janson Industries 2014

Run Time Exceptions

Specific exception generated

Class, method, statement number causing exception

Page 18: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 18© copyright Janson Industries 2014

Run Time Exceptions

▮ It's doCalc that

▮ Converts the text field data to numeric

▮ Does the divide

▮ These statements can cause ▮ NumberFormat and Arithmetic exceptions

Page 19: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 19© copyright Janson Industries 2014

Catching Exceptions

▮ Programs can catch exceptions

▮ Catching tells JVM that the application will handle the exception

▮ Why catch?▮ Solve the problem programmatically▮ Offer users chance to fix problem▮ Display better messages (than the

JVM) so users can fix the problem

Page 20: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 20© copyright Janson Industries 2014

Try and Catch

▮ Try identifies statements that may throw an exception

▮ Catch(es):▮ Immediately follow try▮ Identify the exception to be caught▮ Contain code to handle the specific

exception try {

statements that may throw an exception

}

catch (exception_object_type exception_variable) {

statements to perform if specific exception occurs

}

Page 21: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 21© copyright Janson Industries 2014

RAD and Exceptions

▮ RAD will put in try and catch(es) for the appropriate exceptions that can be thrown▮ Highlight statement(s)▮ Click Source, Surround With, Try/catch Block

▮ Alternatively, specify the Exception superclass and all subclasses will be caught▮ catch (Exception e) { } catches any

exception

▮ Sloppy programming?

Page 22: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 22© copyright Janson Industries 2014

private void doCalc() {

msgBeginning = new String("The result of ");

msgVerb = new String(" ");

try {

firstNum = Double.valueOf(numeratorTF.getText());

secondNum = Double.valueOf(denominatorTF.getText());

} catch (NumberFormatException e) {

resultLbl.setForeground(Color.red);

resultLbl.setText("You must enter the value " +

"in number format (ex: 9, 192.4, etc.)");

}

: : : : :

Try and Catch

Must import java.awt.Color also

Page 23: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 23© copyright Janson Industries 2014

Let RAD do it for you

Page 24: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 24© copyright Janson Industries 2014

Get rid of the stack trace print and …

Page 25: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 25© copyright Janson Industries 2014

… add error handling code into catch

Page 26: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 26© copyright Janson Industries 2014

When run - oops

Also, when valid data re-entered and executed...

Page 27: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 27© copyright Janson Industries 2014

What's going on?

... the valid message is red.

Page 28: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 28© copyright Janson Industries 2014

Catching an Exception

▮ Also, catching an exception does not stop the program execution

▮ So, need to change code such that:▮ If input error, no calculation is done ▮ Reset result label text color to black

▮ Lots of ways to implement this:▮ Need a new Boolean variable to indicate

if the data is valid/invalid▮ Create a separate input validation

method

Page 29: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 29© copyright Janson Industries 2014

Moved validation from doCalc to validateInput

private boolean isInputValid;

Add code to create the boolean class level variable

Page 30: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

▮ At beginning of validateInput, add code to reset label color and boolean value

▮ When exception caught set boolean to false

▮ actionPerformed and itemStateChanged invoke validateInput first and if isInputValid is true, invoke doCalc

Chapter 7 30© copyright Janson Industries 2014

Catching an Exception

isInputValid = true;

resultLbl.setForeground(Color.black);

Page 31: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 31© copyright Janson Industries 2014

Page 32: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 32© copyright Janson Industries 2014

Doh! – the error msg doesn't fit

Run to test

Page 33: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 33© copyright Janson Industries 2014

Throwing an Exception

▮ Usually there are lots of edits & audits on input data and class must throw exceptions

▮ For instance, negative numbers should not be accepted but do not cause an exception▮ Check for negative values (with an if)▮ If negative, throw an exception▮ Have the catch:

▮ Blank out the negative value(s)▮ Display a message

Page 34: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 34© copyright Janson Industries 2014

Throwing an Exceptiontry {

: : : :

if ((firstNum<0) || (secondNum<0)) {

throw new NumberFormatException(); } }

catch (NumberFormatException err){

: : : :

if (firstNum < 0) {

numeratorTF.setText(" ");

resultLbl.setText("Quit messin' with negative numbers!");

}

if (secondNum < 0) {

denominatorTF.setText(" ");

resultLbl.setText("Quit messin' with negative numbers!");

} }

Page 35: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 35© copyright Janson Industries 2014

Page 36: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 36© copyright Janson Industries 2014

Click on

Divide

The negative number is erasedAnd the message is displayed

Page 37: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 37© copyright Janson Industries 2014

StringBuffers

▮ More efficient than Strings:

▮ Strings are immutable▮ Assigning a new value to a String variable

creates a new String object▮ Old String object still exists and is

unreferenced

▮ Changing the StringBuffer value does not create a new StringBuffer object

Page 38: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 38© copyright Janson Industries 2014

StringBuffers

▮ More flexible than Strings:

▮ Append – adds text to the end of a string buffer (i.e. concatenates)

▮ Insert – places text at a specified location within a string buffer

▮ Replace – substitutes text for a specified substring within the string buffer

Page 39: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 39© copyright Janson Industries 2014

StringBuffer Examples

▮ Results in: Chicken wings are very tasty.

▮ Results in: Chicken wings are good for you.

StringBuffer a = new StringBuffer("Chicken wings are tasty.");

a.insert(18, "very ");

System.out.println(a);

StringBuffer a = new StringBuffer("Chicken wings are tasty.");

a.replace(18, 23, "good for you");

System.out.println(a);

Page 40: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 40© copyright Janson Industries 2014

StringBuffer

▮ Calculator creates message text unique for each operation

▮ The result of dividing 7 by 2

▮ The result of adding 7 to 2

▮ With Strings:▮ Can only use concatenation▮ Each concatenation creates a new

String Object – very inefficient

Page 41: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 41© copyright Janson Industries 2014

StringBuffer

▮ Append correct arithmetic verb to msgBeginning StringBuffer

if (addBox.getState());

{

msgBegin.append("adding ");

result = firstNum + secondNum;

}

StringBuffer msgBegin =

new StringBuffer("The result of ");

StringBuffer msgPrep = new StringBuffer(" ");

Page 42: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 42© copyright Janson Industries 2014

if (addCB.getState()) {

msgBegin.append("adding ");

msgPrep.append("to ");

result = firstNum + secondNum; }

else { if (subCB.getState()) {

msgBegin.append("subtracting ");

msgPrep.append("from ");

result = firstNum - secondNum; }

else { msgPrep.append("by ");

if (multCB.getState()) {

msgBegin.append("multiplying ");

result = firstNum * secondNum; }

else { if (divCB.getState()) {

msgBegin.append("dividing ");

result = firstNum / secondNum;

}

}

} }

Page 43: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 43© copyright Janson Industries 2014

if (subCB.getState()) {

resultLbl.setText(msgBegin.append(secondNum) .append(msgPrep).append(firstNum)

.append(" is ").append(result).toString());

} else {

resultLbl.setText(msgBegin

.append(firstNum).append(msgPrep)

.append(secondNum).append(" is ")

.append(result).toString());

}

▮ Fix creating the message▮ No concatenation, append▮ To set label, must convert to String

StringBuffer

Page 44: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 44© copyright Janson Industries 2014

Editing Data

▮ The best way to avoid data entry errors is to prevent them▮ Limit the values that can be entered

▮ A Choice component only allows a value from a list of values to be selected and entered

▮ Adv: using one choice instead of many visual components (e.g. checkboxes) means less coding

Page 45: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 45© copyright Janson Industries 2014

Choice

▮ Combines a TextField and drop-down list

▮ To define a choice and populate it with values:Choice schoolsCB = new Choice();

schoolsCB.add(“Harvard”);

schoolsCB.add(“Yale”);

schoolsCB.add(“Princeton”);

schoolsCB.setBounds(162,100,200,20);

this.add(schoolsCB);

Page 46: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 46© copyright Janson Industries 2014

Choice

▮ When user clicks on choice button, the list will be displayed

▮ To retrieve a selected list item:▮ Create and add an ItemListener to the

Choice▮ Define an itemStateChanged method▮ Use getSelectedItem method

public class ChoiceEx extends Frame implements

ActionListener, ItemListener, WindowListener {...

public void itemStateChanged(ItemEvent choice)

{ selectedSchool = schoolsCB.getSelectedItem();

...}

Page 47: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 47© copyright Janson Industries 2014

CalcChoice

▮ Pull it all together:

▮ Use choice instead of checkboxes

//import java.awt.Checkbox;

//import java.awt.CheckboxGroup;

import java.awt.Choice;

Page 48: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 48© copyright Janson Industries 2014

CalcChoice

▮ One Choice instead of four check boxes and a check box group means▮ One variable instead of five▮ One get component method instead of five

public class CalcChoice extends Frame implements ActionListener, ItemListener, WindowListener {

: : : : : :

private Choice arithFuncChoice = null;

//CheckboxGroup arithFunc = new CheckboxGroup();

//private Checkbox multCB = null;

//private Checkbox addCB = null;

//private Checkbox subCB = null;

//private Checkbox divCB = null;

StringBuffer msgBegin = new StringBuffer("The result of ");

StringBuffer msgPrep = new StringBuffer(" ");

Page 49: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 49© copyright Janson Industries 2014

private Choice getArithFuncChoice() {

if (arithFuncChoice == null) {

arithFuncChoice = new Choice();

arithFuncChoice.setBounds(new Rectangle(120, 100, 89, 21));

arithFuncChoice.add("Add");

arithFuncChoice.add("Subtract");

arithFuncChoice.add("Multiply");

arithFuncChoice.add("Divide");

arithFuncChoice.addItemListener(this);

}

return arithFuncChoice;

}

CalcChoice

▮ Added this…

▮ but got rid of…

Page 50: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 50© copyright Janson Industries 2014

//private Checkbox getMultCB() {

// if (multCB == null) {

// multCB = new Checkbox();

// multCB.setBounds(new Rectangle(155, 101, 59, 23));

// multCB.setLabel("Multiply");

// multCB.setCheckboxGroup(arithFunc);

// multCB.addItemListener(this);

// }

// return multCB;

//}

//private Checkbox getAddCB() {

// if (addCB == null) {

// addCB = new Checkbox();

// addCB.setBounds(new Rectangle(18, 101, 43, 23));

// addCB.setLabel("Add");

// addCB.setCheckboxGroup(arithFunc);

// addCB.addItemListener(this);

// }

// return addCB;

//}

Page 51: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 51© copyright Janson Industries 2014

//private Checkbox getSubCB() {

// if (subCB == null) {

// subCB = new Checkbox();

// subCB.setBounds(new Rectangle(75, 101, 66, 23));

// subCB.setLabel("Subtract");

// subCB.setCheckboxGroup(arithFunc);

// subCB.addItemListener(this);

// }

// return subCB;

//}

//private Checkbox getDivCB() {

// if (divCB == null) {

// divCB = new Checkbox();

// divCB.setBounds(new Rectangle(228, 101, 54, 23));

// divCB.setLabel("Divide");

// divCB.setCheckboxGroup(arithFunc);

// divCB.addItemListener(this);

// }

// return divCB;

//}

Page 52: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 52© copyright Janson Industries 2014

//this.add(getMultCB(), null);

//this.add(getAddCB(), null);

//this.add(getSubCB(), null);

//this.add(getDivCB(), null);

CalcChoice

▮ Added this…

▮ but got rid of…

this.add(getArithFuncChoice(), null);

Page 53: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 53© copyright Janson Industries 2014

If Add selected

If Subtract

CalcChoice

▮ Check the Choice value

Page 54: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 54© copyright Janson Industries 2014

if (arithFuncChoice.getSelectedItem()== "Multiply") {

msgBegin.append("multiplying ");

result = firstNum * secondNum;

} else {

if (arithFuncChoice.getSelectedItem()== "Divide") {

msgBegin.append(" dividing ");

result = firstNum / secondNum; }

} } }

if (arithFuncChoice.getSelectedItem()== "Subtract") {

resultLbl.setText(msgBegin.append(secondNum)

.append(msgPrep).append(firstNum).append(" is ")

.append(result).toString());

} else {resultLbl.setText(msgBegin.append(firstNum)

.append(msgPrep).append(secondNum).append(" is ")

.append(result).toString());

}

If multiply

If Divide

CalcChoice

Page 55: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 55© copyright Janson Industries 2014

CalcChoice

Page 56: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

▮ Create CalcChoice such that

▮ Arithmetic operations are in a Choice

▮ Uses a StringBuffer to build the message

▮ Email CalcChoice.java to

[email protected]

Chapter 7 56© copyright Janson Industries 2014

Non-graded Assg

Page 57: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

▮ JVM doesn’t always show info the way you would like

▮ Can manipulate Strings and StringBuffers

▮ But that can get messy Chapter 7 57© copyright Janson Industries 2014

Formatters

Page 58: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 58© copyright Janson Industries 2014

Formatters

▮ Work a little differently▮ You don’t create an instance/object▮ You get an instance from the format

class

▮ 4 steps to format▮ Import format class▮ Get an instance of the formatter from the

format class▮ Set the formatter properties (optional)▮ Use the formatter’s format method

Page 59: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 59© copyright Janson Industries 2014

Number Formatter

▮ Results in: 3.0

3.3333333333333335

34.565

System.out.println(9.0/3.0);

System.out.println(10.0/3.0);

System.out.println(34.565);

Page 60: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 60© copyright Janson Industries 2014

Number Formatter

▮ Results in: 3

3.333

34.565

34.565

import java.text.NumberFormat; : : : :

NumberFormat nf = NumberFormat.getInstance(); : : : :

System.out.println(nf.format(9.0/3.0));

System.out.println(nf.format(10.0/3.0));

System.out.println(nf.format(34.565));

System.out.println(nf.format(34.5651));

Defaults are:3 decimals

maxno decimal

min

Page 61: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 61© copyright Janson Industries 2014

Number Formatter

▮ Results in: 3

3.33

34.56

34.57

import java.text.NumberFormat; : : : :

NumberFormat nf = NumberFormat.getInstance();

nf.setMaximumFractionDigits(2); : : : :

System.out.println(nf.format(9.0/3.0));

System.out.println(nf.format(10.0/3.0));

System.out.println(nf.format(34.565));

System.out.println(nf.format(34.5651));

Page 62: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 62© copyright Janson Industries 2014

Number Formatter

▮ Results in: 3.00

3.33

34.56

import java.text.NumberFormat;

: : : :

NumberFormat nf = NumberFormat.getInstance();

nf.setMaximumFractionDigits(2);

nf.setMinimumFractionDigits(2);

System.out.println(nf.format(9.0/3.0));

System.out.println(nf.format(10.0/3.0));

System.out.println(nf.format(34.565));

Page 63: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 63© copyright Janson Industries 2014

Currency Formatter

▮ Results in…

import java.text.NumberFormat;

: : : :NumberFormat cf = NumberFormat.getCurrencyInstance();

: : : :msgLbl.setText("The cost of this" +

" transaction is: $" + cf.format(cost));

3 items costing $1.77 each with 6.5% tax

▮ Results in: 5.65515

cost =(3 * 1.77) * 1.065

Page 64: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

▮ Currency defaults are usually good enough

Chapter 7 64© copyright Janson Industries 2014

Currency Formatter

Page 65: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 65© copyright Janson Industries 2014

Date and Time Formatters

▮ A little more complicated

▮ First of all, you can get the current date by

▮ Importing java.util.Date

▮ Creating a date objectimport java.util.Date;

: : : : Date d = new Date();

System.out.println(d);

▮ Results in: Tue May 31 13:11:59 EDT 2014

Page 66: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 66© copyright Janson Industries 2014

DateFormat

▮ DateFormat class has predefined formats

▮ To use a DateFormat:▮ Import DateFormat class

▮ Get a DateFormat instance (getDateInstance) and specify the format to use

▮ Create a date object

▮ Use date format object’s format method and pass the date object as a parameter

Page 67: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 67© copyright Janson Industries 2014

DateFormat import java.text.DateFormat; : : : :

Date d = new Date();

DateFormat dfShort= DateFormat.getDateInstance(DateFormat.SHORT);

DateFormat dfMed = DateFormat.getDateInstance(DateFormat.MEDIUM);

DateFormat dfLong = DateFormat.getDateInstance(DateFormat.LONG);

DateFormat dfFull = DateFormat.getDateInstance(DateFormat.FULL);

System.out.println(d);

System.out.println(dfShort.format(d));

System.out.println(dfMed.format(d));

System.out.println(dfLong.format(d));

System.out.println(dfFull.format(d));

Results in: Tue Mar 13 14:38:59 EDT 2012

3/13/12

Mar 13, 2012

March 13, 2012

Tuesday, March 13, 2012

Page 68: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 68© copyright Janson Industries 2014

DateFormat for Time

System.out.println(d.getTime());

DateFormat tfShort = DateFormat.getTimeInstance(DateFormat.SHORT);

DateFormat tfMedium = DateFormat.getTimeInstance(DateFormat.MEDIUM);

DateFormat tfLong = DateFormat.getTimeInstance(DateFormat.LONG);

DateFormat tfFull = DateFormat.getTimeInstance(DateFormat.FULL);

System.out.println(tfShort.format(d));

System.out.println(tfMedium.format(d));

System.out.println(tfLong.format(d));

System.out.println(tfFull.format(d));

Results in: 13068621902251:16 PM1:16:30 PM1:16:30 PM EDT1:16:30 PM EDT

Time stored as a number

In USA, LONG & FULL are the same

Page 69: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 69© copyright Janson Industries 2014

SimpleDateFormat

▮ Allows you to define a format

▮ To use a SimpleDateFormat:▮ Import SimpleDateFormat class▮ Create a SimpleDateFormat object and

specify the format using date format symbols▮y – year, s – seconds, a – (AM or PM)▮M – month, m – minute▮H – hour (0-23), h – hour (1-12)▮d – day of month (1-31), D – day of year▮z – time zone

Page 70: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 70© copyright Janson Industries 2014

SimpleDateFormat

Results: 05/31/201401:19 PM

1 O'clock PM, Eastern Daylight Time

151

import java.text.SimpleDateFormat;

: : : :

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

SimpleDateFormat stf = new SimpleDateFormat("hh:mm a");

SimpleDateFormat st2f = new SimpleDateFormat("h 'O''clock' a, zzzz");

SimpleDateFormat sd2f = new SimpleDateFormat("D");

System.out.println(sdf.format(d));

System.out.println(stf.format(d));

System.out.println(st2f.format(d));

System.out.println(sd2f.format(d));

Page 71: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 71© copyright Janson Industries 2014

Iteration

▮ WHILE and DO WHILE allow looping based on a condition

▮ FOR allows looping for a set number of iterations based on a ▮ Starting value

▮ Increment value

▮ Ending value

Page 72: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 72© copyright Janson Industries 2014

Iteration

▮ WHILE allows looping based on a condition

▮ FOR allows a certain number of iterations

while (eof == 0) {

statements to be repeated;

}

for (int j = 0; j < max; j++) {

statements to be repeated;

}

Page 73: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 73© copyright Janson Industries 2014

Iteration

▮ DO WHILE checks the condition after the statements are executed

▮ Condition is checked at end of loop ▮ Therefore, the loop will be executed at

least once

do {

statements to be repeated;

} while (eof == 0);

Page 74: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 74© copyright Janson Industries 2014

Iteration

▮ BREAK and CONTINUE provide exits from a loop

▮ Results in:

for (int j = 0; j < 5; j++) {

if (j == 2) {

break;

}

System.out.println("j = " + j);

}

j = 0

j = 1

Page 75: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 75© copyright Janson Industries 2014

Iteration

▮ Results in:

for (int j = 0; j < 5; j++) {

if (j == 2) {

continue;}

System.out.println(“j = “ + j);

}

j = 0

j = 1

j = 3

j = 4

Page 76: Chapter 71© copyright Janson Industries 2014 Avoiding Data Entry Errors ▮ Catching an Exception ▮ Formatters ▮ StringBuffer ▮ Choice ▮ Iteration ▮ Method

Chapter 7 76© copyright Janson Industries 2014

Method Overloading

▮ Having methods with the same name but different signatures

▮ Signature = method name + parameters

▮ Why? Overloading makes your class more flexible/easier to use