Week 02 Lecture

Download Report

Transcript Week 02 Lecture

COIT 11222 – Visual Programming
• Lecture:
Week 2
References:
• Java Programming - Complete
Concepts and Techniques,
3rd Edition, Shelly Cashman et al.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 1
Topics For This Week
• Variables: integers, floats, doubles, booleans,
Strings, Dates
• Formatting Output, Escape Chars, etc
• Conditional Statements – if, else, compound if,
nested if, and switch
• SWING Dialogs – Output, Input, and Confirmation
• SWING Dialogs and Escape Chars
• Getting User Input: BufferedReader, Scanner, and
SWING Dialog Input
• Terminating GUI Programs – exit ().
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 2
Variables
• Variables are named memory locations
where data can be stored and manipulated.
• The general form of the code to declare a
variable is:
datatype variableName;
• If you want to declare and initialise a variable:
datatype variableName = value;
• You can change the value of a variable (that
has already been declared) with:
variableName = newvalue;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 3
Variables (cont)
• If you want to declare multiple variables of the same
type, then you can use multiple declarations:
datatype var1;
datatype var2;
... etc ...;
• Or, you can do the same thing on a single line:
datatype var1, var2, ...;
• If you want to initialise some (or all) of these:
datatype var1 = val1;
datatype var2 = val2;
... etc ...;
• Or, you can do the same thing on a single line:
datatype var1 = val1, var2 = val2, ...;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 4
Variables (cont)
• Java supports many data types.
• Primitive Data Types are automatically supported by Java.
e.g. int, float, boolean, etc.
• Java also provides Reference Data Types which are either
automatically supported by Java or need "import"
statements before they can be used. e.g. String, Date.
• However, these can both be infinitely extended.
• For example, programmers can create their own data types
(called User Defined Data Types) based on these and then
use these to declare variables (or further data types). More
on this in a future lecture.
• The data types (in the shaded rows on the next slide) are
the ones you will probably use most in this course.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 5
Primitive Data Types and Strings
Data
Family
Integers
Real
Numbers
Characters
and Strings
Boolean
Data Type
Min Value
Max Value
Precision
Memory
(or min positive
value for Reals)
(or max positive
value for Reals)
(decimal places)
(bytes)
byte
-128
+127
n/a
1
short
-32,768
+32,767
n/a
2
int
-231
+231 - 1
n/a
4
long
-9 * 1018
+9 * 1018 - 1
n/a
8
float
2-149
2128 (approx)
6 or 7
4
double
2-1074
21023 (approx)
14 or 15
8
char
'\u0000'
'\uFFFF'
n/a
2
String
""
Huge
n/a
Size of Str
boolean
false
true
n/a
1
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 6
Assignment Statements
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 7
Variables – Integers
• Integers are whole numbers. e.g. 1, -20, 500.
• Example – Declare only:
int count;
• Example – Declare and initialise:
int total = 0;
• Example – Declare many but only initialise
some:
int min = 5, max = 10, age, k = 3;
• Assignment (field must be declared already):
age = 18;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 8
Variables – Floats and Doubles
• Real numbers, such as floats and doubles, are
integers and all of the fractional numbers in
between. e.g. 1.0, 12.1, -38.234112.
• Example – Declare only:
double avg;
• Example – Declare and initialise:
double total = 0.0;
• Example – Declare and initialise many:
double interest = 6.25, baseCost = 200.25;
• Assignment (field must be declared already):
interest = 6.75;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 9
Arithmetic Operators
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 10
Arithmetic Operators (cont)
• Manipulation: You can assign, add, subtract,
divide, multiply, etc.
• Example – Add:
finalResult = ass1 + ass2 + exam;
• Example – A simple average calculation:
avgResult = (stud1 + stud2 + stud3) / 3.0;
• Example – Another calculation:
net = gross – (cost + (overhd * days / 1.2));
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 11
Arithmetic Operators (cont)
• The Order of Operator Precedence is a
predetermined order that defines the
sequence in which operators are evaluated in
an expression.
• Addition, subtraction, multiplication, and
division can manipulate any numeric data
type.
• When Java performs math on mixed data
types, the result is always the larger data
type.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 12
Arithmetic Operators (cont)
• Unless parentheses supercede, an
expression is evaluated left to right with the
following rules of precedence:
– Multiplication and/or division
– Integer division
– Modular division
– Addition and/or subtraction
• This is similar but not identical to BODMAS
(Brackets of Division, Multiplication, Addition,
and Subtraction).
• Be VERY Careful !!!
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 13
Exercise 1
• Exercise what value would Val have in each case ?
double Val = 20 / 3;
double Val = 20.0 / 3;
double Val = 20 / 3.0;
double Val = 20.0 / 3.0;
double Val = (double)20 / 3;
• Please try and work out the answer(s) before
looking below.
• Solution
Val
Val
Val
Val
Val
=
=
=
=
=
20 / 3
20.0 / 3
20 / 3.0
20.0 / 3.0
(double)20 / 3
COIT 11222 - Visual Programming
=
=
=
=
=
6.0
6.666666666666667
6.666666666666667
6.666666666666667
6.666666666666667
Author(s): Mike O’Malley
Slide: 14
Exercise 2
• Exercise what value would Val have in each
case ?
double Val = 20 / 3 * 6 + 3;
double Val = 20.0 / 3 * 6 + 3;
• Please try and work out the answer(s) before
looking below.
• Solution
Val = 20 / 3 * 6 + 3
Val = 20.0 / 3 * 6 + 3
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
= 39.0
= 43.0
Slide: 15
Exercise 3
• Exercise what value would Val have in each case ?
double Val = 16 / 4 / 3;
double Val = 16.0 / 4 / 3;
double Val = 16 / 4.0 / 3;
double Val = 16 / 4 / 3.0;
double Val = 16.0 / 4.0 / 3.0;
• Please try and work out the answer(s) before
looking below.
• Solution
Val
Val
Val
Val
Val
=
=
=
=
=
16 /
16.0
16 /
16 /
16.0
4 / 3
/ 4 / 3
4.0 / 3
4 / 3.0
/ 4.0 / 3.0
COIT 11222 - Visual Programming
=
=
=
=
=
1.0
1.3333333333333333
1.3333333333333333
1.3333333333333333
1.3333333333333333
Author(s): Mike O’Malley
Slide: 16
Variables - Output
• For most variables, you can output them on
their own or with other data / text / variables
by using the addition (+) operator.
• Examples:
int k = 5;
System.out.println (k);
System.out.println ("k = " + k);
System.out.println ("The value of k is: "
+ k + " KB.");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 17
Variables and Compilation Errors
• If you try and use a variable that has not been
declared in your program, then you will get a
"cannot find symbol symbol : variable …"
compilation error. e.g. if k has not been declared:
System.out.println ("k = " + k);
• If you try and use a variable that has not been
initialised in your program, then you will get a
"variable … might not have been initialized"
compilation error. e.g.
int k;
System.out.println ("k = " + k);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 18
Arithmetic Operators (cont)
• Parentheses may be used to change the
order of operations:
– The part of the expression within the parentheses
is evaluated first.
• Parentheses can provide clarity in complex
expressions:
– Numeric and conditional expressions should be
grouped with parentheses.
• Parentheses can be nested:
– Java evaluates the innermost expression first and
then moves on to the outermost expression.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 19
Arithmetic Operators (cont) Typecasting
• Typecasts allow programmers to force a
conversion from one primitive type to another.
• e.g. convert double to int:
int k = (int)20.3;
int k = (int)myDouble;
• eg. convert int to double:
myDouble = (double)k;
• But, since double is a superset of int, then we
don’t need to cast the above conversion:
myDouble = k;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 20
Variables - Booleans
• Booleans can be true or false.
• Example – Declare only:
boolean finishedInput;
• Example – Declare and initialise:
boolean dataValid = false;
• Example – Declare and initialise many:
boolean flag1 = false, flag2 = true;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 21
Comparison Operators
• A comparison operation results in a true or
false value that can be stored in a boolean
variable.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 22
Conditional Expressions
• Conditional expressions evaluate to either true
or false.
• Comparison operators, values, variables,
methods, and Strings may be used in a
conditional expression.
• Two operands must be separated by a
comparison operator.
• Unless parentheses supercede, an expression
is evaluated left to right with relational
operators (<, <=, >, >=) taking precedence
over equality operators (==, !=).
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 23
Conditional Expressions (cont)
• In Java:
– the AND operator is &&
– the OR operator is ||
– the NOT operator is !
• AND (&&) and OR (||) operators can be used
to join multiple conditions together.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 24
Truth Tables
• Note: 0 = False, 1 = True
Logical AND (&&) Truth Table
Logical OR (||) Truth Table
A
B
A && B
A
B
A || B
0
0
0
0
0
0
0
1
0
0
1
1
1
0
0
1
0
1
1
1
1
1
1
1
Logical NOT (!) Truth Table
COIT 11222 - Visual Programming
A
!A
0
1
1
0
Author(s): Mike O’Malley
Slide: 25
IF
• The main conditional statement in Java is if
… else …
• Example – a simple if:
if (age < 18)
System.out.println ("Young Person");
• Example – a simple if … else … :
if (age < 18)
System.out.println ("Young Person");
else
System.out.println ("Adult");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 26
IF (cont)
• If you need more than one line of code in the
if or the else section, then enclose this in
braces { }. Example:
if (age < 18)
{
youngCount = youngCount + 1;
System.out.println ("Young Person");
}
else
{
adultCount = adultCount + 1;
System.out.println ("Adult");
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 27
Assignment Equals Vs Logical Equals
• Assignment Equals (=) is used to set the
value of a variable to an expression.
• Example:
avgResult = (stud1 + stud2 + stud3) / 3.0;
• Logical Equals (==) is used to compare the
value of two expressions).
• Example:
if (age == 18)
{
System.out.println ("You are 18 !");
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 28
Assignment Equals Vs Logical Equals
(cont)
• CAUTION: You cannot use Assignment
Equals (=) to do the job of Logical Equals
(==) and you cannot use Logical Equals (==)
to do the job of Assignment Equals (=).
• If you attempt to do this, then Java might not
always raise a compilation error, but your
program will not do what you intended.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 29
Assignment Equals Vs Logical Equals
(cont)
• Exercise – what would happen here and why ? (Assume the
code compiles without any errors or warnings).
int age = 20;
if (age = 18)
{
System.out.println ("You are 18 !");
}
System.out.println (age + " years");
• Please try and work out the answer(s) before looking below.
• Solution: The (age = 18) would assign the value 18 to age
(due to using the wrong equals operator, assignment
equals), and the if test would evaluate to true (so the code
inside the if test would be executed), followed by the code
below, giving the following output:
You are 18 !
18 years
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 30
Compound IF
• If there are multiple conditions to evaluate,
then use && and/or || operators. Example:
if ((age < 18) && (male == true))
{
maleYoungCount = maleYoungCount + 1;
System.out.println ("Male Young Person");
}
else
{
adultCount = adultCount + 1;
System.out.println ("Adult");
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 31
Compound IF (cont)
• If you have one or more AND's (&&) and one or
more OR's (||) in a conditional statement, then
always use round brackets to separate them and
specify the order of execution / evaluation.
• Exercise: Do these if tests yield the same results ?
int k = 4, m = 6, p = 12;
if ((k > 1) && (m > p) || (m > k))
System.out.println (" Test 1");
if ((k > 1) && ((m > p) || (m > k)))
System.out.println (" Test 2");
if (((k > 1) && (m > p)) || (m > k))
System.out.println ("Test 3");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 32
Compound IF (cont)
• Please try and work out the answer(s) before
looking below.
• Solution:
int k = 4, m = 6, p = 12;
if ((k > 1) && (m > p) || (m > k))
• No brackets around groups of conditions, so they
are evaluated from left to right, so we have T && F
|| T = F || T = T.
if ((k > 1)
&& ((m > p) || (m > k)))
• Brackets, so we have (T && F ) || T = F || T = T.
if (((k > 1)
&& (m > p)) || (m > k))
• Brackets, so we have (T && (F || T) = T && T = T.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 33
Else IF
• Use else if to add more branches to an if test.
• Example:
if ((age < 18) && (male == true))
System.out.println ("Male Young Person");
else if ((age < 18) && (male == false))
System.out.println ("Female Young Person");
else if ((age >= 18) && (male == true))
System.out.println ("Male Adult");
else if ((age >= 18) && (male == false))
System.out.println ("Female Adult");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 34
Else IF (cont)
• We could achieve exactly the same result as
the above code, but, in this case anyway,
more simply as follows:
if (male == true)
System.out.print ("Male ");
else
System.out.print ("Female ");
if (age < 18)
System.out.println ("Young Person");
else
System.out.println ("Adult");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 35
Nested IF
• A Nested If occurs when an if test is within or inside
another if test.
• Example – here we have an if test inside the if and
the else branches of an if test.
if (male == true)
{
if (age < 18)
System.out.println
else
System.out.println
}
else
{
if (age < 18)
System.out.println
else
System.out.println
}
COIT 11222 - Visual Programming
("Male Young Person");
("Male Adult");
("Female Young Person");
("Female Adult");
Author(s): Mike O’Malley
Slide: 36
Exercise 4
• Exercise: Evaluate this conditional expression (and
show your working !):
int k = 4, m = 6, p = 12;
if (((k > 1)
((k > m)
&& ((m < p) || (m < k)))
|| (k > p/m)))
&&
• Please try and work out the answer(s) before
looking below.
• Solution:
if (((k > 1) && ((m < p) || (m < k))) &&
((k > m) || (k > p/m))) //[p/m = 12/6 = 2]
=> ( ( T && (T || F)) && (F || T))
=> (T && T) && T
=> T
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 37
Variables - Strings
• Strings are one or more characters.
• Example – Declare only:
String streetName;
• Example – Declare and initialise:
String streetName = "Bruce Hwy";
• Example – Declare and initialise many:
String uniName = "CQU", campus = "Rocky";
• Assignment (field must be declared already):
uniName = "Central Qld University";
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 38
Variables – Strings (cont)
• To join (concatenate) strings, use the addition
(+) operator. Examples:
String streetName = "Bruce Hwy";
String uniName = "CQU", campus = "Rocky";
String fullAddress;
fullAddress = "I visited: " + uniName + ", " +
streetName + ", " + campus + ".";
System.out.println (fullAddress);
• You can do this concatenation at any time, for
example, even in an output statement:
System.out.println ("On Monday, " +
fullAddress + " to see my friends.");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 39
Variables – Strings (cont)
• To join (concatenate) strings, integers, floats, and
doubles into a string, use the addition (+) operator.
Examples:
double avgResult = 79.0;
int
avgAge
= 25;
String studDetails;
studDetails = "Average Age = " + avgAge +
", Average Result = " + avgResult;
System.out.println (studDetails);
• As before, you can do this concatenation at any
time, for example, even in an output statement:
System.out.println ("For COIT11222, " + studDetails + "
- excellent !!");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 40
Variables – Strings (cont)
• Here is the output produced by the above code:
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 41
Comparing Strings – use compareTo
• CAUTION: Java lets you use Logical Equals (==) to
compare strings, but this is NOT 100% reliable.
• Do NOT use Logical Equals (==) to compare
strings.
• Use the compareTo function instead, which is called
as follows:
string1.compareTo (string2)
• which evaluates to:
0
>0
<0
if the strings are identical.
if the string1 > string2
if the string1 < string2
• Example:
if (uniName.compareTo ("CQU") == 0)
System.out.println ("Be What You Want To Be");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 42
Import
• Not all of the functionality available in Java is
automatically available for use.
• Support for additional "non-default" functionality is
provided by import statements.
• The general form of the import statement is:
import ...;
• For example to obtain support for Dates in Java,
you can use:
import java.util.Date;
// For Date support.
• Or, if you want to import all of the functionality
provided in the java.util package, use:
import java.util.*;
COIT 11222 - Visual Programming
// For Date, etc support.
Author(s): Mike O’Malley
Slide: 43
Import (cont)
• Some people are very particular about their import
statements, and they frown on the use of "*" to bring
in "all of a package". For example, the following
would be frowned on:
import java.util.*; // For Date, etc support.
import java.text.*; // For formatting, etc support.
• Some people much prefer you to nominate what
you are using in each package. For example:
import java.util.Date;
import java.text.SimpleDateFormat;
// Date support.
// Date formatting.
• Keep this in mind for the future.
• However, in this course, feel free to use whichever
method you prefer.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 44
Output Formatting – Escape Chars
• The following Escape Characters can be used to
help format the output in print and println
commands.
• Note: Some of the Escape Characters also work
with Swing dialogs.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 45
//
//
//
Output Formatting – Escape Chars
(cont)
Author:
Mike O'Malley
Source File: W02_08a_Formatting_Escape_Chars.java
Description: Using Escape Chars to format output.
public class W02_08a_Formatting_Escape_Chars
{
public static void main (String[] args)
{
System.out.println ("\n\nName\tCity\tScore\n-----\t-----\t-----\n");
System.out.println ("Mike\tRocky\t12.5\nBoogle\tRocky\t15.0\n");
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 46
Output Formatting – Numeric
• If you output a float or double, then it may be displayed in an
undesirable format (scientific notation, too many decimal
places, etc).
• If you output a large number (integer, float, double, etc), then
you may want comma separators for the thousands.
• To format any number, we need to import the number
formatting package:
import java.text.DecimalFormat; // Number Formatting.
• Then, we can create a number format and use this to format
numeric output. For example, to have a comma thousands
separator and 2 decimal places:
Double val = 123456.12345678;
DecimalFormat formatCS2DP = new DecimalFormat ("###,##0.00");
System.out.println ("Formatted: " + formatCS2DP.format (val));
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 47
Output Formatting – Numeric (cont)
• Here is the complete console application program:
//
//
//
Author:
Mike O'Malley
Source File: W02_08_Formatting_Numbers.java
Description: Number formatting examples.
import java.text.DecimalFormat;
// For Number Formatting.
public class W02_08_Formatting_Numbers
{
public static void main (String[] args)
{
Double val = 123456.12345678;
// Comma thousands separator, 2 decimal places.
DecimalFormat formatCS2DP
= new DecimalFormat ("###,##0.00");
System.out.println (" Unformatted: " + val);
System.out.println ("
Formatted: " + formatCS2DP.format (val));
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 48
Output Formatting – Numeric (cont)
• Here is the output of this program:
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 49
Variables - Dates
• Dates are special Reference Data Types in
Java, and your program requires an import
statement to be able to use them. Example:
import java.util.Date;
// For Date support.
• Dates also need to be declared in a special
way, using the new keyword. For example, to
declare a date and initialise it the current
system date:
Date myDate = new Date ();
• Once we have done this, we can output the
Date as we do any other variable. Example:
System.out.println (myDate);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 50
Variables – Dates - Formatting
• The date is output in the "default format".
• If we want to override this and specify our own
format, then we need to import the date formatting
package:
import java.text.SimpleDateFormat; // Date Formatting.
• and we can then create a date format and use this
to format the date how we want. For example:
SimpleDateFormat myFormat = new SimpleDateFormat
("EEE, dd-MMM-yyyy");
System.out.println (myFormat.format (myDate));
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 51
Variables – Dates – Output
Formatting
MMMM is the same as
more than four M's, such
as MMMMMMM – the
entire day of the month
name is output. For
example, "November"
would be displayed for
both.
EEEE is the same as
more than four E's, such
as EEEEEEE – the entire
day of the week name is
output. For example,
"Tuesday" would be
displayed for both.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 52
Variables – Dates – Output
Formatting (cont)
• Here is the complete console application program:
//
//
//
Author:
Mike O'Malley
Source File: W02_09_Dates_and_Formats.java
Description: Date formatting examples.
import java.util.Date;
import java.text.SimpleDateFormat;
// For Date support.
// For SimpleDateFormat support.
public class W02_09_Dates_and_Formats
{
public static void main (String[] args)
{
Date myDate = new Date ();
System.out.println ("Default Format: " + myDate);
SimpleDateFormat myFormat = new SimpleDateFormat("EEE,dd-MMM-yyyy");
System.out.println ("
My Format: " + myFormat.format (myDate));
}
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 53
Variables – Dates – Output
Formatting (cont)
• Here is the output of this program:
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 54
Constants
• Constants are fields whose values you do not want
to change during execution of the program.
• Threshold values, conversion factors, minimum and
maximum values, prompts, error messages, etc are
all ideal candidates for being constants.
• To declare a constant, use the final keyword.
• Also, make your constant names UPPERCASE so
they are easily identifiable in your code. Examples:
final int MIN_AGE
= 10;
final int MAX_AGE
= 120;
final double GST_PCT = 0.10;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 55
Conversions: Number → String
• To convert numbers (integers, floats, etc) to
Strings, there are a range of functions you
can use.
• For example, concatenate the number onto
the string using the addition (+) operator:
int
avgAge
= 25;
String studDetails = "Average Age = " + avgAge;
• Or, use format (covered earlier):
// Comma thousands separator, 2 decimal places.
DecimalFormat formatCS2DP = new DecimalFormat ("###,##0.00");
Double val = 123456.12345678;
String valString = "Val = " + formatCS2DP.format (val);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 56
Conversions: Number → String (cont)
• Or, use toString :
int
avgAge
= 25;
String studDetails = Integer.toString(avgAge);
// Dec
• This converts to a string with a radix of 10
(decimal number system).
• If you want to convert an integer a different
radix, such as octal or hexadecimal, then
specify the radix. Example:
studDetails = Integer.toString(avgAge, 16); // Hex
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 57
Conversions: String → Number
• To convert Strings to integers, doubles, etc, there
are also a range of functions available.
• For example, parseInt and parseDouble:
Double val = Double.parseDouble("12.34");
int avgAge = Integer.parseInt("1234");
• If invalid data is encountered, then these methods
raise exceptions. For example:
int avgAge = Integer.parseInt("1234xyz");
• Unhandled exceptions will cause your program to
crash. For now, we will have to live with this.
• In a future lecture, we will cover exception handling.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 58
Built-in Functions
• Recommendations:
– In this course we cover a very small fraction of
the functionality provided by Java.
– Do NOT be afraid to explore.
– Java provides many 1,000's of functions, so
learning what is available could save you
reinventing the wheel and a lot of time and work
as well.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 59
Getting User Input
• For Java console applications, there are 3
main methods to get user input:
– BufferedReader
– Scanner
– SWING Input Dialogs
• All of these methods are covered on the
following slides.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 60
Getting User Input - BufferedReader
• BufferedReader is the oldest and most
complex way to obtain user input.
• For BufferedReader, all data comes in as a
string – the method is called readLine - and
then convert it to integer, double, etc as
required. e.g. use parseInt and parseDouble.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 61
Getting User Input – BufferedReader
(cont)
• First step to use BufferedReader, you need to
import the desired functionality:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
• Next step, to use BufferedReader, we need to
add "throws IOException" to our main
method:
public static void main (String[] args) throws IOException
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 62
Getting User Input – BufferedReader
(cont)
• Next, we need to declare a BufferedReader
object, for example:
BufferedReader keyboardIn = new BufferedReader
(new InputStreamReader (System.in));
• Where:
– System.in is the default input device, the
keyboard.
– InputStreamReader reads input from the
keyboard.
– BufferedReader provides a buffer for this input.
– keyboardIn allows us to get input from the user.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 63
Getting User Input – BufferedReader
(cont)
• Example #1: now let's use keyboardIn to get
a string from the user:
String
empName = "";
System.out.print ("Enter Employee Name
empName = keyboardIn.readLine ();
: ");
• Example #2: and also get an integer from the
user (Remember: everything is a string !):
int
hours
= 0;
String
hoursStr = "";
System.out.print ("Enter Hours Worked : ");
hoursStr = keyboardIn.readLine ();
hours
= Integer.parseInt (hoursStr);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 64
Getting User Input - Scanner
• Scanner is more poweful and easier to use
than BufferedReader.
• Like BufferedReader, you can read all data
comes in as a string – the method is called
nextLine NOT readLine - and then convert it
to integer, float, etc as required. e.g. use
parseInt and parseDouble.
• Or, you can use additional methods that
Scanner provides, such as nextInt and
nextDouble, to directly read in integers,
doubles, etc.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 65
Getting User Input – Scanner (cont)
• First step to use Scanner, you need to import
the desired functionality:
import java.util.Scanner;
• Unlike BufferedReader, we do NOT need to
have "throws IOException" on our main
method for Scanner.
• So, this is what we need for our main:
public static void main (String[] args)
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 66
Getting User Input – Scanner (cont)
• Next, we need to declare a Scanner object,
for example:
Scanner keyboardIn = new Scanner (System.in);
• Where:
– System.in is the default input device, the
keyboard.
– keyboardIn allows us to get input from the user.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 67
Getting User Input – Scanner (cont)
• Example #1: now let's use keyboardIn to get
a string from the user:
String
empName = "";
System.out.print ("Enter Employee Name
empName = keyboardIn.nextLine ();
: ");
• Example #2: and also get an integer from the
user (Remember: everything is a string !):
int
hours
= 0;
System.out.print ("Enter Hours Worked : ");
hours
= keyboardIn.nextInt ();
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 68
SWING Dialogs
• SWING Dialogs are attractive, graphical dialogs that
can be used to:
– Display output,
– Prompt the user to enter input,
– Prompt the user to confirm a course of action.
• All of these dialog types are covered on the
following slides.
• You can use all types of SWING dialogs with all of
the Java application types we cover this term:
Console Applications, Applets, and Windowed
Applications.
• To use SWING dialogs, you need to import:
import javax.swing.JOptionPane;
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 69
SWING Dialogs - Output
• A SWING Output Dialog is used to display output to
the user.
• The general form is:
JOptionPane.showMessageDialog (null,
"message text", "title message",
JOptionPane.type_of_message);
• Where type_of_message is one of these:
– INFORMATION_MESSAGE
– ERROR_MESSAGE
– WARNING_MESSAGE
• These affect the icon that is displayed on the dialog.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 70
SWING Dialogs – Output (cont)
• Examples:
JOptionPane.showMessageDialog (null,
"Gross Pay = " + grossPay,
"Gross Pay",
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog (null,
"Gross Pay = " + grossPay,
"Gross Pay",
JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog (null,
"Gross Pay = " + grossPay,
"Gross Pay",
JOptionPane.WARNING_MESSAGE);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 71
SWING Dialogs and Escape Chars
• Note: Some of the Escape Characters (see earlier
slide) also work with Swing dialogs (but some do
not). Example:
JOptionPane.showMessageDialog (null,
"Name\tCity\tScore\n-----\t-----\t-----\n" +
"Mike\tRocky\t12.5\nBoogle\tRocky\t15.0\n",
"Escape Chars",
JOptionPane.INFORMATION_MESSAGE);
• \n works fine
• \t does not work
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 72
SWING Dialogs - Input
• SWING Input Dialogs prompt the user for input.
• Like BufferedReader, all data comes in as a string.
If required, convert this to integer, double, etc. e.g.
use parseInt and parseDouble.
empID
=
("Enter
hoursStr =
("Enter
JOptionPane.showInputDialog
Employee ID: ");
JOptionPane.showInputDialog
Hours Worked: ");
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 73
SWING Dialogs - Confirmation
• A SWING Confirmation Dialog is used to prompt the user to
confirm a course of action.
• Example
int Result = 0;
Result = JOptionPane.showConfirmDialog (null,
"Process this order ? Are you sure ?",
"Process Order ?",
JOptionPane.YES_NO_OPTION);
if (Result == JOptionPane.YES_OPTION)
{
// User Clicked "Yes" ... process this order.
}
else
{
// User Clicked "No" ...
}
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 74
Terminating GUI Programs – exit()
• System.exit() terminates an application that
displays a GUI
– The Command Prompt window also closes when
this method is called.
• System.exit () accepts an integer argument
that serves as a status code:
– 0 indicates successful termination and that the
program finished without error.
– Non-zero (usually -1 or 1 are used) to indicate
abnormal termination or that some sort of
irrecoverable or unhandled error has occurred.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 75
Terminating GUI Programs – exit()
(cont)
• Example #1 - A serious error occurred, so the
program should give the user as much information
as possible, so they can understand the errors and,
if necessary, report them to the programmer(s) so
they can be analysed / fixed / handled:
if (Errors_Detected == true)
{
System.err.println ("ERROR: Program terminating " +
"due to serious errors in database connection, " +
"in method XYZ, source file ABC.java, etc ...");
System.exit(-1);
// Exit due to a serious error.
}
• Example #2 – Program ending normally:
System.exit(0);
COIT 11222 - Visual Programming
// Program is ending normally.
Author(s): Mike O’Malley
Slide: 76
Case Selection - Switch
• The switch selection structure allows multiple
integer values to be evaluated, via one or more
case statements.
• case statements are evaluated in turn. If the
condition(s) for a case statement are satisfied, then
the code within the particular case statement is
executed.
• Each case statement normally contains an ending
break statement which forces an exit of the
structure.
• An optional default statement may also be used,
and the code in this section is executed only if none
of the other case statements are satisfied.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 77
Case Selection – Switch (cont)
• If a break statement is missing, then the code
in all following case statement(s) will also be
processed, until either:
– a break statement is encountered, or,
– the end of the switch structure is encountered.
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 78
Case Selection – Switch (cont)
//
//
//
Author:
Mike O'Malley
Source File: W02_14_Switch.java
Description: Read in user input and display output using Swing Dialogs.
import javax.swing.JOptionPane;
// For Swing Dialogs
public class W02_14_Switch
{
public static void main (String[] args)
{
int
weekType;
String weekTypeStr;
// Get User Input
weekTypeStr = JOptionPane.showInputDialog
("Enter the Category for Hours Worked (0=no work, " +
"1=light, 2=standard, 3=heavy): ");
// Convert to Integers
weekType
= Integer.parseInt(weekTypeStr);
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 79
Case Selection – Switch (cont)
switch (weekType)
{
case 0: System.out.println ("No Work this week !!");
System.out.println ("Oh well, maybe next week ...");
break;
case 1: System.out.println ("A light week this week ... ");
System.out.println ("Maybe you'll get more hours next week ...");
break;
case 2: System.out.println ("A standard week ...");
break;
case 3: System.out.println ("A heavy week this week ...");
System.out.println ("Hope you have an easier week next week !!");
break;
default: System.out.println ("**Error: Category " + hoursStr +
" is not valid !");
break;
}
// Exit
System.exit(0); // Program is ending normally.
} // public static void main
} // public class W02_14_Switch
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 80
Exercise 5
• Exercise what would happen if we removed all of
the break statements from the prior example, and
the value of weekType was 2 ? What would the
user see on screen ?
• Solution
• All of the code inside all case statements from 2
onwards would be executed - yes, even the code in
the “default” section is executed !!
• The user would see this:
A standard week ...
A heavy week this week ...
Hope you have an easier week next week !!
**Error: Category 2 is not valid !
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 81
Summary of Topics Covered
• Variables: integers, floats, doubles, booleans,
Strings, Dates
• Formatting Output, Escape Chars, etc
• Conditional Statements – if, else, compound if,
nested if, and switch
• SWING Dialogs – Output, Input, and Confirmation
• SWING Dialogs and Escape Chars
• Getting User Input: BufferedReader, Scanner, and
SWING Dialog Input
• Terminating GUI Programs – exit ().
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 82
End of Lecture
COIT 11222 - Visual Programming
Author(s): Mike O’Malley
Slide: 83