Avoiding Errors - Florida State College at Jacksonville
Download
Report
Transcript Avoiding Errors - Florida State College at Jacksonville
Avoiding Data Entry Errors
▮ Catching an Exception
▮ Formatters
▮ StringBuffer
▮ Choice
▮ Iteration
▮ Method Overloading
Non-graded Assg
Chapter 7
© copyright Janson Industries 2014
1
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)
Chapter 7
© copyright Janson Industries 2014
2
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…
Chapter 7
© copyright Janson Industries 2014
3
Normally a user:
Enters valid values
Clicks the Divide button
Result is displayed in the label
Chapter 7
© copyright Janson Industries 2014
4
Entering the incorrect value “four”
and clicking Divide does not result
in an exception being displayed on
the Frame...
Chapter 7
... it's displayed in the console
© copyright Janson Industries 2014
5
Run Time Exceptions
Or worse yet, in production
Is this how the user should see an exception/error?
Chapter 7
© copyright Janson Industries 2014
6
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…
Chapter 7
© copyright Janson Industries 2014
7
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.Frame;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.ItemEvent;
java.awt.event.ItemListener;
java.awt.event.WindowEvent;
java.awt.event.WindowListener;
java.awt.CheckboxGroup;
java.awt.Label;
java.awt.Rectangle;
java.awt.TextField;
java.awt.Checkbox;
java.awt.Button;
java.awt.Point;
java.awt.Dimension;
Calculator Code
Various imports
public class Calculator extends Frame implements ActionListener,
WindowListener, ItemListener {
private static final long serialVersionUID = 1L;
private Label numeratorLbl = null;
private Label denominatorLbl = null;
private TextField numeratorTF = null;
private TextField denominatorTF = null;
private Checkbox multCB = null;
private Checkbox addCB = null;
private Checkbox subCB = null;
Various
variables
Chapter 7
© copyright Janson Industries 2014
8
private Checkbox divCB = null;
private Button exitBtn = null;
Make result, firstNum, and
private Button execBtn = null;
secondNum class level variables
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) {}
WindowListener methods
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitBtn)
{ System.exit(0);}
else
{this.doCalc();}}
Action Listener
method
public void itemStateChanged(ItemEvent e) {
this.doCalc();
© copyright Janson Industries 2014
} Chapter 7
Item Listener
method
9
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
{
Chapter 7
© copyright Janson Industries 2014
10
The workhorse
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();
}
Chapter 7
main
Constructor
© copyright Janson Industries 2014
11
Visual component objects
private 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);
}
private Checkbox getMultBox() {
return addBox;
if (multBox == null) {
}
multBox = new Checkbox();
multBox.setBounds(new Rectangle(155,101, 59, 23));
private Checkbox getSubBox() {
multBox.setLabel("Multiply");
if (subBox == null) {
multBox.setCheckboxGroup(arithFunc);
subBox = new Checkbox();
multBox.addItemListener(this);
subBox.setBounds(new Rectangle(75, 101, 66,
23));
}
subBox.setLabel("Subtract");
return multBox;
subBox.setCheckboxGroup(arithFunc);
}
subBox.addItemListener(this);
private Checkbox getDivBox() {
}
if (divBox == null) {
return subBox;
divBox = new Checkbox();
}
divBox.setBounds(new Rectangle(228, 101, 54, 23));
divBox.setLabel("Divide");
divBox.setCheckboxGroup(arithFunc);
divBox.addItemListener(this);
}
return divBox;
Chapter 7
© copyright Janson Industries 2014
12
}
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);
private Button getExecBtn() {
}
if (execBtn == null) {
return exitBtn;
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
© copyright Janson Industries 2014
13
}
Visual component
objects
initialize
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);
}
}
Chapter 7
© copyright Janson Industries 2014
14
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
Chapter 7
© copyright Janson Industries 2014
15
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
Chapter 7
© copyright Janson Industries 2014
16
Run Time Exceptions
Specific exception generated
Class, method, statement number causing exception
Chapter 7
© copyright Janson Industries 2014
17
Run Time Exceptions
▮ It's doCalc that
▮ Converts the text field data to numeric
▮ Does the divide
firstNum = Double.valueOf(numeratorTF.getText());
secondNum = Double.valueOf(denominatorTF.getText());
:
:
:
:
:
result = firstNum / secondNum;
▮ These statements can cause
▮ NumberFormat and Arithmetic exceptions
Chapter 7
© copyright Janson Industries 2014
18
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
Chapter 7
© copyright Janson Industries 2014
19
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
© copyright Janson Industries 2014
20
} Chapter 7
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?
Chapter 7
© copyright Janson Industries 2014
21
Try and Catch
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.)");
}
:
:
:
:
:
Must import java.awt.Color also
Chapter 7
© copyright Janson Industries 2014
22
Let RAD do it for you
Chapter 7
© copyright Janson Industries 2014
23
Get rid of the stack trace print and …
Chapter 7
© copyright Janson Industries 2014
24
… add error handling code into catch
Chapter 7
© copyright Janson Industries 2014
25
When run - oops
Also, when valid data re-entered and executed...
Chapter 7
© copyright Janson Industries 2014
26
... the valid message is red.
What's going on?
Chapter 7
© copyright Janson Industries 2014
27
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
Chapter 7
© copyright Janson Industries 2014
28
Moved validation from doCalc to validateInput
Add code to create the boolean class level variable
private boolean isInputValid;
Chapter 7
© copyright Janson Industries 2014
29
Catching an Exception
▮ At beginning of validateInput, add code
to reset label color and boolean value
isInputValid = true;
resultLbl.setForeground(Color.black);
▮ When exception caught set boolean to
false
▮ actionPerformed and itemStateChanged
invoke validateInput first and if
isInputValid is true, invoke doCalc
Chapter 7
© copyright Janson Industries 2014
30
Chapter 7
© copyright Janson Industries 2014
31
Run to test
Doh! – the error msg doesn't fit
Chapter 7
© copyright Janson Industries 2014
32
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
Chapter 7
© copyright Janson Industries 2014
33
Throwing an Exception
try {
:
:
:
:
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!");
}
}
Chapter 7
© copyright Janson Industries 2014
34
Chapter 7
© copyright Janson Industries 2014
35
Click on
Divide
The negative number is erased
And the message is displayed
Chapter 7
© copyright Janson Industries 2014
36
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
Chapter 7
© copyright Janson Industries 2014
37
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
Chapter 7
© copyright Janson Industries 2014
38
StringBuffer Examples
StringBuffer a = new StringBuffer("Chicken wings are
tasty.");
a.insert(18, "very ");
System.out.println(a);
▮ Results in:
Chicken wings are very tasty.
StringBuffer a = new StringBuffer("Chicken wings are
tasty.");
a.replace(18, 23, "good for you");
System.out.println(a);
▮ Results in:
Chicken wings are good for you.
Chapter 7
© copyright Janson Industries 2014
39
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
Chapter 7
© copyright Janson Industries 2014
40
StringBuffer
StringBuffer msgBegin =
new StringBuffer("The result of ");
StringBuffer msgPrep = new StringBuffer(" ");
▮ Append correct arithmetic verb to
msgBeginning StringBuffer
if (addBox.getState());
{
msgBegin.append("adding ");
result = firstNum + secondNum;
}
Chapter 7
© copyright Janson Industries 2014
41
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;
}
}
© copyright Janson Industries 2014
42
} Chapter
}7
StringBuffer
▮ Fix creating the message
▮ No concatenation, append
▮ To set label, must convert to String
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());
}
Chapter 7
© copyright Janson Industries 2014
43
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
Chapter 7
© copyright Janson Industries 2014
44
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);
Chapter 7
© copyright Janson Industries 2014
45
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();
Chapter 7
© copyright Janson Industries 2014
46
...}
CalcChoice
▮ Pull it all together:
▮ Use choice instead of checkboxes
//import java.awt.Checkbox;
//import java.awt.CheckboxGroup;
import java.awt.Choice;
Chapter 7
© copyright Janson Industries 2014
47
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("
Chapter 7
© copyright
Janson Industries 2014");
48
CalcChoice
▮ Added this…
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;
}
▮ but got rid of…
Chapter 7
© copyright Janson Industries 2014
49
//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;
//} Chapter 7
© copyright Janson Industries 2014
50
//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;
//} Chapter 7
© copyright Janson Industries 2014
51
CalcChoice
▮ Added this…
this.add(getArithFuncChoice(), null);
▮ but got rid of…
//this.add(getMultCB(), null);
//this.add(getAddCB(), null);
//this.add(getSubCB(), null);
//this.add(getDivCB(), null);
Chapter 7
© copyright Janson Industries 2014
52
CalcChoice
▮ Check the Choice value
private void doCalc() {
if (arithFuncChoice.getSelectedItem()== "Add") {
msgBegin.append("adding ");
msgPrep = msgPrep.append("to ");
result = firstNum + secondNum;
} else {
if (arithFuncChoice.getSelectedItem()== "Subtract") {
msgBegin.append("subtracting ");
msgPrep = msgPrep.append("from ");
result = firstNum - secondNum;
} else {
msgPrep = msgPrep.append("by ");
If Add selected
If Subtract
Chapter 7
© copyright Janson Industries 2014
53
CalcChoice
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());
© copyright Janson Industries 2014
54
} Chapter 7
If multiply
If Divide
CalcChoice
Chapter 7
© copyright Janson Industries 2014
55
Non-graded Assg
▮ 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
© copyright Janson Industries 2014
56
Formatters
▮ JVM doesn’t always show info the way
you would like
▮ Can manipulate Strings and StringBuffers
▮ But that can get messy
Chapter 7
© copyright Janson Industries 2014
57
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
Chapter 7
© copyright Janson Industries 2014
58
Number Formatter
System.out.println(9.0/3.0);
System.out.println(10.0/3.0);
System.out.println(34.565);
▮ Results in:
Chapter 7
3.0
3.3333333333333335
34.565
© copyright Janson Industries 2014
59
Number Formatter
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));
▮ Results in:
Chapter 7
3
3.333
Defaults are:
3 decimals max
34.565
no decimal
min
© copyright
Janson Industries
2014
34.565
60
Number Formatter
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));
▮ Results in:
Chapter 7
3
3.33
34.56
© copyright
Janson Industries 2014
34.57
61
Number Formatter
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));
▮ Results in:
Chapter 7
3.00
3.33
34.56
© copyright Janson Industries 2014
62
Currency Formatter
3 items costing $1.77 each with 6.5% tax
cost =(3 * 1.77) * 1.065
▮ Results in:
5.65515
import java.text.NumberFormat;
:
:
:
:
NumberFormat cf = NumberFormat.getCurrencyInstance();
:
:
:
:
msgLbl.setText("The cost of this" +
" transaction is: $" + cf.format(cost));
▮ Results in…
Chapter 7
© copyright Janson Industries 2014
63
Currency Formatter
▮ Currency defaults are usually good enough
Chapter 7
© copyright Janson Industries 2014
64
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 object
import java.util.Date;
:
:
:
:
Date d = new Date();
System.out.println(d);
▮ Results in: Tue May 31 13:11:59 EDT 2014
Chapter 7
© copyright Janson Industries 2014
65
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
Chapter 7
© copyright Janson Industries 2014
66
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:
Chapter 7
Tue Mar 13 14:38:59 EDT 2012
3/13/12
Mar 13, 2012
March 13, 2012
© copyright Janson Industries 2014
Tuesday, March 13, 2012
67
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:
Chapter 7
1306862190225 Time stored as
a number
1:16 PM
1:16:30 PM
In USA, LONG &
1:16:30 PM EDT FULL are the
1:16:30 PM EDT
same
© copyright Janson Industries 2014
68
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
Chapter 7
© copyright Janson Industries 2014
69
SimpleDateFormat
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));
Results:
Chapter 7
05/31/2014
01:19 PM
1 O'clock PM, Eastern Daylight Time
© copyright Janson Industries 2014
70
151
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
Chapter 7
© copyright Janson Industries 2014
71
Iteration
▮ WHILE allows looping based on a condition
while (eof == 0) {
statements to be repeated;
}
▮ FOR allows a certain number of iterations
for (int j = 0; j < max; j++) {
statements to be repeated;
}
Chapter 7
© copyright Janson Industries 2014
72
Iteration
▮ DO WHILE checks the condition after
the statements are executed
do {
statements to be repeated;
} while (eof == 0);
▮ Condition is checked at end of loop
▮ Therefore, the loop will be executed at
least once
Chapter 7
© copyright Janson Industries 2014
73
Iteration
▮ BREAK and CONTINUE provide exits from
a loop
▮
for (int j = 0; j < 5; j++) {
if (j == 2) {
break;
}
System.out.println("j = " + j);
}
Results
in:
j = 0
j = 1
Chapter 7
© copyright Janson Industries 2014
74
Iteration
for (int j = 0; j < 5; j++) {
if (j == 2) {
continue;}
System.out.println(“j = “ + j);
}
▮ Results in:
Chapter 7
j
j
j
j
=
=
=
=
0
1
3
4
© copyright Janson Industries 2014
75
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
Chapter 7
© copyright Janson Industries 2014
76