Chapter 6© copyright Janson Industries 20141 Java ▮ Comparing Strings/Objects ▮ Conditional...
-
Upload
david-carpenter -
Category
Documents
-
view
215 -
download
0
Transcript of Chapter 6© copyright Janson Industries 20141 Java ▮ Comparing Strings/Objects ▮ Conditional...
Chapter 6 © copyright Janson Industries 2014 1
Java▮ Comparing Strings/Objects
▮ Conditional logic▮ if/else▮ switch
▮ More GUI▮ Check boxes▮ Item listeners▮ Using Event objects
▮ Debugging
▮ Preferences Non-graded Assg
Chapter 6 © copyright Janson Industries 2014 2
Comparisons
▮ Highlights the difference between primitive and referenced variablesint a = 5; int b = 5
boolean isEqual = (a == b);
String a = new String(“Joe”);
String b = new String(“Joe”);
boolean isEqual = (a == b);
isEqual is TRUE
isEqual is FALSE
Chapter 6 © copyright Janson Industries 2014 3
Referenced Variables
▮ Contain the memory address of the value
▮ Defining two strings objects, means memory is allocated like this:
▮ And a = A1, b = B2
A B C
1 Joe
2 Joe
3
a
b
Chapter 6 © copyright Janson Industries 2014 4
Comparisons
▮ So when we compare
▮ Because address A1 does not equal B2
boolean isEqual = (a == b);
isEqual is FALSE
Chapter 6 © copyright Janson Industries 2014 5
String▮ If we change the value of a
▮ The value “Art” is placed in memory
▮ a = C3 and the first Joe is not referenced
a = new String(“Art”);
A B C
1 Joe
2 Joe
3 Art
ab
Chapter 6 © copyright Janson Industries 2014 6
String▮ However if we define a new string
▮ c = C3 (it points to the object a points to)
▮ c == a is TRUE
String c = a;
A B C
1 Joe
2 Joe
3 Art
abc
Chapter 6 © copyright Janson Industries 2014 7
Primitive Variables ▮ Defining these two integers:
▮ Results in a memory allocation of:int a = 1; int b = 2;
A B C
1 1
2 2
3
Chapter 6 © copyright Janson Industries 2014 8
Primitives
▮ If we change the value of a
▮ The value 1 is replaced with 3
a = 3;
A B C
1 3
2 2
3
Chapter 6 © copyright Janson Industries 2014 9
Comparing Strings
▮ String has the equals method for comparing the text of two StringsString a = new String(“Joe”);
String b = new String(“Joe”);
boolean isEqual = (a.equals(“Joe”));
boolean isEqual = (a.equals(b));
boolean isEqual = (a.equals(“JOE”));
boolean isEqual = (a.equalsIgnoreCase(“JOE”));
isEqual is TRUE
isEqual is FALSE
isEqual is TRUE
Chapter 6 © copyright Janson Industries 2014 10
IF/ELSE
▮ Syntax of an if/else statement▮ if(boolean expression) { statements to be
executed if true } else { statements to be executed if false }
if (gender.equals(“F”)) {
genderLabel.setText(“Female”);
}
else {
genderLabel.setText(“Male”);
}
Chapter 6 © copyright Janson Industries 2014 11
Nested IF
if (month == 1) {
monthLabel.setText(“Jan”);}
else {if (month == 2) {
monthLabel.setText(“Feb”);}
else { if (month == 3) {
monthLabel.setText(“Mar”);}
else { if (month == 4) {………
Nested if
▮ Placing an if statement as one of the statements to be executed in an else clause
Chapter 6 © copyright Janson Industries 2014 12
Try It Exercise
▮ Create a Java class called Month as a subclass of Frame that:
▮ Accepts a number from 1 to 12 (via a text field)
▮ Has button that when clicked displays the associated month name (January, etc.) in a label
▮ Use nested ifs
Chapter 6 © copyright Janson Industries 2014 13
How to Tackle the Exercise▮ CALTAL!
▮ Using VE create the frame with components, then TEST that it displays correctly
▮ Add code such that when button clicked, data read from textfield and placed in label – TEST IT
▮ Code the first if that checks for value = 1 and puts January in label – TEST IT
▮ Code first nested if for value = 2 and display February – TEST IT
▮ Add code for remaining ifs and TEST IT
Chapter 6 © copyright Janson Industries 2014 14
Switch
switch (month) {
case 1: monthLabel.setText(“Jan”); break;
case 2: monthLabel.setText(“Feb”); break;
case 3: monthLabel.setText(“Mar”); break;
: : : : :
: : : : :
default: System.out.println(“Not a valid
month!”);
}
Chapter 6 © copyright Janson Industries 2014 15
Switch
▮ To make the switch work like an if, need the break statements because once the condition is true, all subsequent statements are executed
▮ In the example, if there were no breaks:▮ The label would be set to Dec
▮ The “Not a valid month” message would be displayed
Chapter 6 © copyright Janson Industries 2014 16
Try It Exercise
▮ Create a Java class called month as a subclass of Frame that:
▮ Accepts a number from 1 to 12 (via a text field)
▮ Has button that when clicked displays the associated month name (January, etc.) in a label
▮ Use a switch
Chapter 6 © copyright Janson Industries 2014 17
dispose();
▮ System.exit(0) ends the JVM▮ All open Frames are closed
▮ dispose() ▮ In a frame subclass, closes only that
frame▮ dispose() means this.dispose()
▮ When creating an Exit button use System.exit(0)
▮ When window close button clicked, use dispose();
Chapter 6 © copyright Janson Industries 2014 18
Putting it all to work
▮ When a check box is selected or the Execute button is clicked▮ Calculator will perform a simple arithmetic
calculation between 2 non-negative numbers
▮ Display a message with the result
Chapter 6 © copyright Janson Industries 2014 19
Check Boxes
▮ Appear as a small, square text field with an attached label
▮ The text field acts a toggle switch. Click it and a check mark will appear.
▮ Click again the check mark is removed
Chapter 6 © copyright Janson Industries 2014 20
Check Boxes
▮ Check boxes can be grouped
▮ Grouped check boxes are round
▮ Within a grouped check box only one check box can be checked
▮ Checking a box unchecks any other checked box
Chapter 6 © copyright Janson Industries 2014 21
Check Box & GroupCheckboxGroup arithFunc = new CheckboxGroup(); : : : : : :
Checkbox addCB = new Checkbox();
addCB.setLabel("Add");
addCB.setCheckboxGroup(arithFunc);
addCB.setBounds(new Rectangle(24, 80, 40, 23)); : : : : : :
Checkbox subCB = new Checkbox();
subCB.setLabel("Subtract");
subCB.setCheckboxGroup(arithFunc);
subCB.setBounds(new Rectangle(74, 80, 40, 23)); : : : : : :
this.add(getaddCB(), null);
this.add(getsubCB(), null);
this.add(getmultCB(), null);
this.add(getdivCB(), null);
Chapter 6 © copyright Janson Industries 2014 22
Check Boxes
▮ To work with check boxes, import the classes and implement ItemListener
▮ Then add listeners to the checkboxes and buttons
public class IOExcept extends Frame implements
WindowListener, ActionListener, ItemListener {
addCB.addItemListener(this);
subCB.addItemListener(this);
multCB.addItemListener(this); divCB.addItemListener(this);
execBtn.addActionListener(this);
exitBtn.addActionListener(this);
Chapter 6 © copyright Janson Industries 2014 23
Check Boxes
▮ ItemListener requires an itemStateChanged method (like ActionListener requires actionPerformed) that contains the action to take when a box is checked
▮ Within itemStateChanged get the “state” (true or false) of a box to determine which box was checked▮ checkBox.getState(); //returns a boolean value
public void itemStateChanged(ItemEvent choice) { java statements }
Chapter 6 © copyright Janson Industries 2014 24
Example
▮ Application needs to:▮ Perform the selected arithmetic operation▮ Create message text unique to each
operation ▮ The result of dividing 7 by 2▮ The result of adding 7 to 2
▮ Need to concatenate to the message String based on the selected math function
String msgBegin = new String("The result of ");
String msgPrep = new String(" "); //i.e. "by", "to", "from"
double result, firstNum, secondNum;
firstNum = Double.valueOf(numeratorTF.getText());
secondNum = Double.valueOf(denominatorTF.getText());
Chapter 6 © copyright Janson Industries 2014 25
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 {
if (divCB.getState()) {
msgBegin = msgBegin + "dividing ";
result = firstNum / secondNum;} } } }
Chapter 6 © copyright Janson Industries 2014 26
▮ Build and display the message
▮ Assuming you want this to happen when a checkbox is clicked, all the previous code goes into itemStateChanged
Example
resultLbl.setText(msgBegin + firstNum + msgPrep + secondNum + " is " + result);
Chapter 6 © copyright Janson Industries 2014 27
Run Calculator
Chapter 6 © copyright Janson Industries 2014 28
Enter dataSelect function
Message oops!
Chapter 6 © copyright Janson Industries 2014 29
Check Boxes and Buttons
▮ If execute button clicked, calculation should be performed
▮ Problem:
▮ All the code to do the calc is in ItemStateChanged
▮ When button clicked, actionPerformed executed
Chapter 6 © copyright Janson Industries 2014 30
Check Boxes and Buttons
▮ Move all the ItemStateChange code into separate method (aka doCalc)
▮ Have both itemStateChanged and actionPerformed execute doCalc
▮ Problem is there are two buttons - how do you know which button was clicked?
▮ The event object has which button was clicked
Chapter 6 © copyright Janson Industries 2014 31
New doCalc called by both
But if you click Exit button, doCalc will be performed
Chapter 6 © copyright Janson Industries 2014 32
Using Events
▮ .getSource() returns the object’s address that was involved with the event
▮ If an ActionListener is tied to many buttons, the ActionEvent’s getSource() method returns the button object’s address that was clicked
▮ In actionPerformed, use ifs to figure out which button:
if (e.getSource() == exitBtn) {
System.exit(0);
} else {
this.doCalc();}
Chapter 6 © copyright Janson Industries 2014 33
Now if Exit clicked, application ended
Chapter 6 © copyright Janson Industries 2014 34
Using Events
▮ Also works for Item Listeners and Item Events
▮ Instead of checking each components state, use the ItemEvent
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == addCB) {…}
else if (e.getSource() == subCB) {…}
else if (e.getSource() == multCB)…
Chapter 6 © copyright Janson Industries 2014 35
Using Events
▮ Notice that the if compares the (Button or Check box) variable to what is returned by getSource()
▮ So, what is returned by getSource()?
▮ Or, asked another way, what is in the Button variable?
Chapter 6 © copyright Janson Industries 2014 36
Non-graded Assg
▮ Create Calculator such that it
▮ Performs arithmetic functions and displays correct msgs when checkbox checked or execute button clicked
▮ doCalc checks for which checkbox was clicked
▮ Exit button and Execute button work correctly
▮ Send Calculator.java to [email protected]
Chapter 6 © copyright Janson Industries 2014 37
Java Error Handling
▮ Syntax/compilation errors
▮ How shown
▮ Help
▮ Run time exceptions
▮ Debug Perspective
Chapter 6 © copyright Janson Industries 2014 38
Java Error Handling
▮ Some preferences you might want to change
▮ Have line numbers shown
▮ Run time error msgs will often display the line number of the offending statement
▮ Have RAD
▮ Insert tokens automatically
▮ Stop some messages
▮ Format the source code
Chapter 6 © copyright Janson Industries 2014 39Click Window then Preferences
Chapter 6 © copyright Janson Industries 2014 40
Expand General, Editors, then click on Text Editors
Click the Show line numbers checkbox
Chapter 6 © copyright Janson Industries 2014 41
Click the Semicolons and Braces checkboxes
Expand Java then Editor and click on Typing
Chapter 6 © copyright Janson Industries 2014 42
Suppress certain annoying warnings
Chapter 6 © copyright Janson Industries 2014 43
You can control the content of comments …
Chapter 6 © copyright Janson Industries 2014 44
and the code that is automatically generated
Chapter 6 © copyright Janson Industries 2014 45
Open an edit session and click Source, Format (or Ctrl+Shift+F)
You can also have RAD format your source
Chapter 6 © copyright Janson Industries 2014 46
Chapter 6 © copyright Janson Industries 2014 47
Like WORD, errors underlined with a red squiggly line in the source code
Errors also indicated by a red circle (with a white X) in the marker bar to the left of the
line number
Chapter 6 © copyright Janson Industries 2014 48
Display flyover error message by moving cursor over the error icon on left
Chapter 6 © copyright Janson Industries 2014 49
Light bulb icon (behind error icon) means RAD has some suggestions for fixing the error
Click the light bulb to display suggestions and solutions
Double click a solution and RAD will implement the code in the right hand pane
Chapter 6 © copyright Janson Industries 2014 50
Have to be a sharpshooter to hit that light bulb icon
Alternative: move the cursor over the red squiggly line to display a list of suggestions
Click a suggestion, RAD will implement the solution code
Chapter 6 © copyright Janson Industries 2014 51
RAD not perfect!Label problem no longer
flagged New error distracts RAD
(Squirrel!!)
Chapter 6 © copyright Janson Industries 2014 52
After saving/compiling, errors also indicated in Explorer & Outline views & the Workspace view
tab
Chapter 6 © copyright Janson Industries 2014 53
Pink rectangles on right show errors in entire program
Clicking on a pink rectangle moves cursor to the error in the source code and shows that line of
code
Chapter 6 © copyright Janson Industries 2014 54
Lots of Compilation Errors
▮ Errors can cascade, best way to find errors is to code and compile in pieces (caltal)
▮ Instead of entering entire program:▮ Code part▮ Test▮ If errors, fix▮ Repeat until no errors▮ Code next portion▮ Repeat process
▮ Solve errors from top to bottom
Chapter 6 © copyright Janson Industries 2014 55
Runtime Errors
▮ The most insidious of all errors
▮ Program compiles and executes but generates incorrect results
▮ Time honored (aka cave man) technique is to display as the program executes
▮ I.e. use System.out.println() in source code to display variable values or messages that indicate the logic path
Chapter 6 © copyright Janson Industries 2014 56
Runtime Errors
▮ RAD provides the common debugger functions of
▮ Setting breakpoints
▮ Stepping through statements
▮ Tracing variables during program execution
▮ Breakpoints are designated lines of code where program execution is halted when the program is run in Debug mode
Chapter 6 © copyright Janson Industries 2014 57
To define a breakpoint:
Move the cursor to the marker bar directly left of the line number
Double click
A small blue circle will be displayed
To remove: double click blue circle
Chapter 6 © copyright Janson Industries 2014 58
To run in Debug: Right click fileSelect Debug AsJava Application
Chapter 6 © copyright Janson Industries 2014 59
Confirm switch to Debug perspective
Chapter 6 © copyright Janson Industries 2014 60
5 panes - Yikes!
Shows where you are in the source code
Thread shows how you got to the breakpoint•Started in main and got to line 9 •The constructor was invoked (Errors.<init>()) and executed until line 15•The initialize method was invoked and run until line 22
Chapter 6 © copyright Janson Industries 2014 61
Debugging Functions
▮ Stepping through the program one line at a time
▮ Use the step into for most detail
▮ or F5
▮ But more often you will use the step over
▮ or F6
Chapter 6 © copyright Janson Industries 2014 62
Step over (F6) causes line 22 to be executed
Notice new variable name and its value is added in Variables view...
And current line changed to 23
Step into (F5) would have sent us into the String class' constructor
Chapter 6 © copyright Janson Industries 2014 63
Can also display String variable value by moving cursor over variable in source code
Variables view lets you see all object properties assigned to variable
Chapter 6 © copyright Janson Industries 2014 64
Selecting the variable in the Variables view displays basic info (toString info)
Chapter 6 © copyright Janson Industries 2014 65
If we step over again (i.e. execute line 23) notice change in label text property
Chapter 6 © copyright Janson Industries 2014 66
Resumes execution
Ends execution
Chapter 6 © copyright Janson Industries 2014 67
End Debug by right clicking debug perspective button and choosing Close
Chapter 6 © copyright Janson Industries 2014 68
Some run time exceptions will result in stack trace displayed in console
RAD added links to particular line numbers
Chapter 6 © copyright Janson Industries 2014 69
Clicking the line number selects and displays the statement
Chapter 6 © copyright Janson Industries 2014 70
Another Helpful Feature
▮ In source, clicking to the right of a parenthesis, brace, bracket (left or right)…
▮ Displays the paired parenthesis, brace, bracket (or what the editor thinks is the paired token) with a gray line around it
▮ Invaluable when trying to track down mismatched parentheses
Chapter 6 © copyright Janson Industries 2014 71