CISC121 - PowerPoint PPT Presentation

1 / 78
About This Presentation
Title:

CISC121

Description:

{ System.out.println('Cannot open file!'); System.exit(0); Scanner fileInput = new Scanner(fileIn) ... The demo only used the chooser in the most simple way. ... – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 79
Provided by: researchC
Category:
Tags: cisc121 | critical

less

Transcript and Presenter's Notes

Title: CISC121


1
CISC121 Lecture 3
  • Last time
  • Lots of fundamental Java
  • Console I/O
  • Conditionals
  • Loops
  • For reading
  • File I/O
  • Exceptions
  • Note exam time has been changed to 16 August
    (Thursday) at 9 to noon, in WLH.

2
You Should Have
  • Finished reading the lecture notes on File I/O
    and Exceptions.
  • Finished Exercise 1.
  • Tried and then looked over the solutions to the
    old assignment 1.
  • Started assignment 1. Contacted a TA if you
    dont know how to get started or are stuck.

3
You Will Need To
  • Finish assignment 1 by Thursday. (I wanted to
    leave time for you to meet with a TA to get
    help.)
  • From todays notes, read about Wrapper classes
    and Strings. The API is your best reference for
    these classes.

4
What I Need To Do
  • Put together a new assignment!
  • Put together some new exercises.

5
Today
  • Write a small sample program finding prime
    numbers.
  • A quick look at exceptions to make sure you
    understand what is going on.
  • Aside - Used with File I/O JFileChooser.
  • Style and Documentation
  • Aside Java keywords
  • Class members Attributes and Methods.
  • Arrays 1-D and Multi-D
  • Passing parameters by value and by reference

6
Exceptions From Last Lecture
  • Text file input example
  • FileReader fileIn null
  • try
  • fileIn new FileReader(filename)
  • catch (FileNotFoundException e)
  • System.out.println("Cannot open file!")
  • System.exit(0)
  • Scanner fileInput new Scanner(fileIn)

7
Exceptions From Last lecture
  • A method can throw more than one kind of
    exception. Why would you want to do this?
  • You can also include more than one line of code
    that can throw an exception inside a try block.
    Why would you not want to do this?

8
Built - In GUI Windows
  • Easy to use, pre-designed GUI dialog boxes
  • JOptionPane
  • JColorChooser
  • JFileChooser
  • Imported from the javax.swing package.
  • See BuiltInDemo.java.

9
JFileChooser
  • A built in file browser/selector dialog box.
  • The demo only used the chooser in the most simple
    way.
  • For example, you can specify a starting folder
    and add as many file extension filters as you
    like.
  • The chooser returns a File object, from which you
    can obtain much information about the file.

10
Simple Alternative
  • Prompt the user for a filename as a String, using
    the console window.
  • But if the user has to supply a path too?...

11
Aside - File Paths in Strings
  • Sometimes you might have to include a path in the
    filename, such as C\Alan\CISC121\Demo.txt
  • Dont forget that if you have to include a \ in
    a String, use \\, as in
  • C\\Alan\\CISC121\\Demo.txt

12
Programming Style Documentation
  • Purpose is to make your code readable (and
    debuggable) by you or another programmer who is
    familiar with the Java language.
  • Internal style elements are documentation
    (comments), spacing, and descriptive variable
    names.
  • Select the conventions you want to use and be
    consistent.
  • (We will discuss creating external documentation
    through the use of the Javadoc utility later.)

13
Programming Style Documentation Cont.
  • Comments
  • Add a block comment to the top of the class and
    at the beginning of each method. Describe
    overall purpose of class/method, main algorithm
    used, author, date created, and any assumptions
    made and/or bugs found. Method comments should
    state what parameters are expected by the method
    and what the method returns.
  • Comments for variable declarations, when the name
    of variable is not self-explanatory.
  • Comments at the beginnings of logical blocks of
    code.
  • In-line comments to indicate the closing brackets
    of blocks and what they close.

14
Programming Style Documentation Cont.
  • Spacing (alignment)
  • Class definition header starts at column 1, and
    closing bracket on column 1.
  • Indent of about 3 or 4 spaces is adequate.
  • Method headers and instance variable declarations
    indented once.
  • Code inside any block, including method code
    indented once from alignment of method header, or
    outer block.

15
Programming Style Documentation Cont.
  • Opening can be at the end of a statement line
    or on the line and position immediately below the
    declaration line
  • public static void main (String args)
  • or
  • public static void main (String args)

16
Programming Style Documentation Cont.
  • Closing on same column as the column where
    the method header is declared, or the statement
    containing the opening . is usually by
    itself on a line.
  • Add a comment after to indicate what is being
    closed.
  • If you have an overlong line, it is OK to
    continue the line on the line below, but indent
    the continued part of the line. (Note do not
    try to continue a line in the middle of a String
    literal!)

17
Programming Style Documentation Cont.
  • Spacing (white space)
  • Add blank lines before and after methods and
    larger logical blocks.
  • One statement per line. (Longer statements can
    be broken onto multiple lines.)
  • Use a space before , ( and . Use a space
    after ) and (unless the next character is
    ).
  • No code after or on same line.
  • No space after ( or before ). (Not too
    critical!)
  • Use space after , or in parameter lists or
    for loop arguments, but not before.
  • Put a space on both sides of an operator.
  • No space before .

18
Do
  • public class StyleDemo
  • public static int someSum (int num1, int
    num2)
  • int sum num1 num2
  • return sum
  • // end someSum method
  • // end StyleDemo class

Of course, this still needs comments for the
class and for the method.
19
Dont!
  • public class StyleDemo
  • public static int s(int l,int l1)
  • int Sll1 return S
  • Look at Sll1 in Times New Roman Font
  • Sll1

20
Roedy Greens Unmaintainable Code
  • See
  • http//mindprod.com/jgloss/unmain.html
  • In the interests of creating employment
    opportunities in the Java programming field, I am
    passing on these tips from the masters on how to
    write code that is so difficult to maintain, that
    the people who come after you will take years to
    make even the simplest changes. Further, if you
    follow all these rules religiously, you will even
    guarantee yourself a lifetime of employment,
    since no one but you has a hope in hell of
    maintaining the code. Then again, if you followed
    all these rules religiously, even you wouldn't be
    able to maintain the code!

21
Programming Style Documentation Cont.
  • Variable Names
  • Also applies to method and class names.
  • Follow java restrictions on names
  • Use only letters, numeric digits (0 to 9) and the
    _ character.
  • Cannot start name with a number.
  • Java is case sensitive!
  • Variables and method names usually start with a
    lower case character. Class names start with an
    upper case character. Constants are all in upper
    case.
  • Variables are usually nouns.
  • Methods are verbs or verbs and nouns.

22
Programming Style Documentation Cont.
  • Be descriptive, but not excessive!
  • Examples
  • numStudents
  • setPassingGrade ( parameter list )
  • Somewhat too long
  • flagThatIsSetToTrueIfAProblemArisesWhenThereIsAFul
    lMoonOverMyHouseInTheWinterWhileMyProgramIsRunning
  • It is OK to use single letter variable names such
    as i, j, k for counters in loops.

23
Programming Style Documentation Cont.
  • The java compiler ignores all white space
    including space characters, tabs and carriage
    return/line feed characters.
  • Note that java keywords are in lower case.
  • You will get an error message if you attempt to
    use a keyword as a variable name.
  • Speaking of keywords

24
Java Keywords
?
?
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte for new throw
case final package throws
catch finally private transient
char float protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfg
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
25
Java Keywords Primitive Types
?
?
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte for new throw
case final package throws
catch finally private transient
char float protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfg
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
26
Java Keywords - Loops
?
?
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte for new throw
case final package throws
catch finally private transient
char float protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfg
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
27
Java Keywords - Conditionals
?
?
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte for new throw
case final package throws
catch finally private transient
char float protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfg
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
28
Java Keywords - Exceptions
?
?
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte for new throw
case final package throws
catch finally private transient
char float protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfg
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
29
Java Keywords Class Method Headers
?
?
abstract double int super
assert else interface switch
boolean enum long synchronized
break extends native this
byte for new throw
case final package throws
catch finally private transient
char float protected try
class goto public void
const if return volatile
continue implements short while
default import static
do instanceof strictfg
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
30
Instance Variables
  • Also called class variables or attributes or
    fields.
  • These variables are declared at the same level as
    the methods in a class.
  • They are known to all methods within a class.
    Their scope is the entire class in which they
    were declared.
  • They are the only variables accessible from
    outside the class, as well, provided they have
    not been declared to be private.
  • Class attributes are not global variables!

31
Instance Variables, Cont.
  • The syntax for the declaration of attributes
  • privatepublic static final type
    variable_name literal_value
  • The in this syntax means one or the other.
  • The means that this part is optional.

32
Instance Variables, Cont.
  • private or public determines if the attribute can
    be accessed from outside the class.
  • If private or public is not stated, then the
    access is protected, by default.
  • A static attribute shares only a single memory
    location, regardless of how many times its class
    is instantiated. So, every instantiation shares
    this attribute, and any of them can change it.
  • Otherwise, the declaration of an attribute is
    just the same as any other variable declaration.

33
Aside - Instantiation???
  • Simply put, it is the creation of a new Object,
    an instance, using the new keyword.
  • Another Object is required to provide the
    pattern for the new Object
  • String aString new String(Hello class!)
  • int anArray new int1000
  • Scanner input new Scanner(System.in)

Instances
34
Aside - More About static
  • Attributes that are used by a class main method
    must be declared static.
  • Methods invoked by main that are in the same
    class as main must be declared static.
  • That is because main is static.
  • If you forget, dont worry, the compiler will
    remind you!

35
Methods
  • The syntax for simple method declaration
  • privatepublic static return_type method_name
    (parameter_list)

36
Methods - Cont.
  • Often, utility methods that are only used by
    other methods within a class are kept private.
  • When the static keyword is used with methods,
    it means that the method can be used without
    instantiation. (All the methods in the Math
    class are static, for example.)
  • When a static method is invoked for the first
    time, it is loaded into memory and then will stay
    in memory until the program completes.

37
Methods - Cont.
  • A method must also have a return_type.
  • A return type is what the method will return. It
    can be any single Object or a primitive type.
    (For example an int, double, String, an array,
    or any other pre-defined Object.)
  • If the method does not return anything, then the
    keyword void is used instead.
  • The main method does not return any value, so
    thats why it is declared as in
  • public static void main (String args)

38
Methods - Cont.
  • parameter_list provides a means of passing items,
    or parameters, into a method.
  • It is optional.
  • It can consist of one or many parameters,
    separated by commas.
  • Each parameter type must be declared in the
    parameter list.

39
Methods - Cont.
  • Also important Unless the return type is void,
    the method must contain at least one return
    statement. A void method can also use a return
    statement without anything after it, as a means
    of termination of the method.
  • A method always stops (terminates) when a return
    statement is encountered.
  • Syntax
  • return literalexpression

40
Methods - Cont.
  • The type of literalexpression must match the
    return type specified in the method declaration
    statement.

41
Method Examples
  • public void printHello()
  • System.out.println(Hello)
  • // end printHello
  • public void printHelloName(String yourName)
  • System.out.println(Hello yourName)
  • // end printHelloName
  • public void printAvg(int a, int b)
  • System.out.println((a b) / 2.0)
  • // end printAvg

42
Method Examples - Cont.
  • public double average(double a, double b)
  • return (a b) / 2
  • // end average
  • public int lowest(int a, int b)
  • if (a lt b)
  • return a
  • else
  • return b
  • // end lowest

43
Methods - Cont.
  • Why use methods?
  • Avoids repetitious code.
  • Independent testing of sub-tasks.
  • Reusable code.
  • Design and test a method once, and re-use it
    whenever you need to solve a similar problem.
  • Isolation from unintended side effects.
  • The only variables from the caller that can be
    seen from a method are those in the argument
    list.
  • Fits in well with modular design practices.

44
Methods - Cont.
  • Start thinking of your program as a collection of
    methods, where the main method only acts to call
    the other methods.
  • Using good modular class design techniques with
    methods and private attributes is called
    encapsulation or information hiding.
  • (More on this starting Thursday?)

45
Methods - Cont.
  • When designing method operations, make sure a
    method only does one thing, do not combine
    operations (except in main).
  • Concentrate on coding the individual methods, one
    at a time, when you write a program.
  • If you have thought out the code-level
    interface between the methods, then the methods
    will be completely independent of each other.
  • Try to minimize the size of the main method, if
    possible. However, if the main method is going
    to be responsible for screen I/O then more code
    may be necessary.

46
One-Dimensional Arrays
  • An array is just a collection of items, stored in
    computer memory (RAM).
  • In Java
  • The items must all be of the same base type.
  • Can be of any primitive type or object.
  • The size of the array must be declared before any
    items can be stored.
  • The size of the array cannot be changed after
    declaration.
  • An array occupies a contiguous memory space.
  • Array elements are numbered from zero.

47
One-Dimensional Arrays - Cont.
  • The use of arrays in memory offers great speed
    advantages over processing data in and out of
    files.
  • File operations are always much slower than
    operations dealing only in RAM.
  • Typically, you will write array programs to
  • Read values from a file.
  • Carry out all the calculations and manipulations
    required, in memory.
  • Save the data back to another file.
  • Arrays make it much easier to carry out the same
    calculation on many values.

48
One-Dimensional Arrays - Declaration
  • For example, to create an array to hold 10
    integers
  • int testArray new int10
  • testArray now points to an area of memory that
    holds locations for 10 integers.
  • It also points to one location that holds
    testArray.length which is an attribute of the
    array, that is equal to the number of elements.
  • Arrays are Objects in Java.

49
One-Dimensional Arrays - Declaration, Cont.
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0

0480ff
0180ff
int testArray 0480ff
  • As a pointer, testArray points to an area of
    memory that contains a series of int values as
    well as the attribute length.

10
.length
50
One-Dimensional Arrays - Declaration, Cont.
  • The java statement above can be split into two
  • int testArray
  • testArray new int10
  • The first statement creates a variable of type
    int - that is to say that it will be an array
    of ints.
  • The variable, testArray is now an object of type
    int that contains an object reference or a
    pointer. The object reference is null after the
    first statement.

51
One-Dimensional Arrays - Declaration, Cont.
  • int testArray
  • testArray new int10
  • The second statement looks for a chunk of memory
    big enough to contiguously hold 10 integers
    (about 40 bytes), and then changes the object
    reference of testArray from null to the memory
    location of the chunk.
  • This assignment of the object reference of the
    testArray object is carried out by the
    assignment operator.
  • The new keyword is responsible for blocking out
    the memory space and initializing each memory
    location to the default value for a new memory
    location of type int (zero).

52
One-Dimensional Arrays - Cont.
  • Back to the 10 array elements in memory
  • testArray0
  • testArray1
  • testArray2
  • testArray3
  • testArray4
  • testArray5
  • testArray6
  • testArray7
  • testArray8
  • testArray9

0 0 0 0 0 0 0 0 0 0
testArray.length
10
53
One-Dimensional Arrays - Indices
  • The numbers 0 to 9 are called the index values of
    the array. The notation used above allows you to
    refer to individual elements.
  • Note that the elements of the array are numbered
    from zero.
  • arrayname.length returns the number of elements
    in the array.

54
One-Dimensional Arrays - Cont.
  • for loops are often used with arrays. For
    example, to initialize each of the elements of
    testArray to the value 1000 i
  • int i
  • for (i 0 i lt 10 i)
  • testArrayi 1000 i
  • Arrays can also be initialized at declaration,
    using an array initializer. To get the same
    array as above
  • int testArray 0, 1000, 2000, 3000, 4000,
    5000, 6000, 7000, 8000, 9000

55
One-Dimensional Arrays - Cont.
  • Arrays can also be created using a variable (or
    constant) to specify the array size
  • final int MAX_SIZE 1000
  • int testArray new intMAX_SIZE
  • int size testArray.length // size is 1000

56
One-Dimensional Arrays - Cont.
  • All the examples so far, have been arrays of
    ints.
  • Could be arrays of doubles, booleans or even
    Strings (anything in fact, as long as all the
    array elements are the same thing)
  • For example

57
More Declaration Examples
  • double dArray new double50
  • String sArray new String100
  • String sArray2 Hi, Ho, Silver!
  • Note that there is some flexibility in where the
    first set of goes. These two declarations
    are equivalent
  • double disNDat new double1000
  • double disNDat new double1000

58
One-Dimensional Arrays - Out-of-bounds Error
  • If n is the size of the array, then
  • Array indices (or subscripts) lt 0 or ? n are
    illegal, since they do not correspond to real
    memory locations in the array.
  • These indices are said to be out-of-bounds.
  • Reference to an out-of-bounds index produces an
    out-of-bounds exception, and the program will
    crash if the exception is not caught.

59
Multi-Dimensional Arrays
  • Multi-dimensional arrays are just arrays of
    arrays.
  • For example, to create a two-dimensional array
  • int twoDArray new int1020
  • Holds 200 elements. Initialize each element to
    the sum of its indices, for example
  • int i, j
  • for (i 0 i lt 10 i)
  • for (j 0 j lt 20 j)
  • twoDArrayij i j

60
Multi-Dimensional Arrays - Cont.
  • Everything is the same as for one-dimensional
    arrays, except that you have a set of for
    each dimension.
  • Two-dimensional arrays are suitable for storage
    of a single type of data that would normally be
    viewed in a table with rows and columns.
  • Java does not place any limitation on the number
    of dimensions used in an array.

61
Multi-Dimensional Arrays - Cont.
  • Consider
  • int exArray new int35

0 0 0 0 0
1002fc
int exArray 0480ff
int exArray0 1002fc int exArray1 1010fc in
t exArray2 1201ab
0 0 0 0 0
1010fc
0 0 0 0 0
1201ab
62
Multi-Dimensional Arrays - Cont.
  • So exArray points to three one dimensional
    arrays
  • exArray0
  • exArray1
  • exArray2
  • Each of these arrays has the same length
  • exArray2.length // returns 5

63
Multi-Dimensional Arrays - Cont.
  • int twoDArray new int1020
  • The above is equivalent to
  • int twoDArray
  • twoDArray new int10
  • for (int i 0 i lt 10 i)
  • twoDArrayi new int20
  • As shown above
  • twoDArray.length // gives 10
  • twoDArray0.length // gives 20

64
Multi-Dimensional Arrays - Cont.
  • Ragged Arrays are not square and are legal in
    Java
  • int raggedArray new int5
  • raggedArray0 new int2
  • raggedArray1 new int4
  • raggedArray2 new int6
  • raggedArray3 new int8
  • raggedArray4 new int10

65
Multi-Dimensional Arrays - Cont.
  • Array initializer for two-D array, for example
  • int twoDArray 1, 2, 3,
  • 4, 5, 6,
  • 7, 8, 9,
  • 10, 11, 12
  • System.out.println(twoDArray.length) // 4
  • System.out.println(twoDArray0.length) // 3

66
Aside - Aliasing Objects
  • Arrays are objects, so we can use them to
    demonstrate aliasing.
  • What is the output of the following code segment?
  • int arrayA 1, 2, 3, 4, 5
  • int arrayB 100, 200, 300
  • arrayA arrayB
  • arrayA1 1000
  • System.out.println(arrayB1)
  • System.out.println(arrayA0)

67
Aliasing Objects, Cont.
  • So both arrayA and arrayB point to the same
    array 100, 200, 300
  • Which becomes 100, 1000, 300
  • arrayA and arrayB are aliased.
  • What happens to 1, 2, 3, 4, 5 ?

68
Passing Parameters by Reference
  • The rule for parameter passing into methods is
  • Objects are passed by reference, primitive types
    are passed by value.
  • An object passed into a method through the
    parameter list is aliased to the object outside
    the method.
  • See PassingDemo.java
  • Has a method with two parameters - an array and
    an int - which one(s) will stay changed?
  • Instead of going element by element, if you
    re-assign the array to another array within the
    method, what happens?

69
Passing Arrays by Reference
  • Summary of PassingDemo.java
  • Primitive types are passed by value.
  • Only element by element changes in arrays will
    stick.
  • Re-assigning the array to a pointer that has
    local scope in a method will not stick.

70
Wrapper Classes
  • Sometimes it is necessary for a primitive type
    value to be an Object, rather than just a
    primitive type.
  • Some data structures only store Objects.
  • Some Java methods only work on Objects.
  • Wrapper classes also contain some useful
    constants and a few handy methods.

71
Wrapper Classes - Cont.
  • Each primitive type has an associated wrapper
    class
  • Each wrapper class Object can hold the value that
    would normally be contained in the primitive type
    variable, but now has a number of useful static
    methods.

char Character
int Integer
long Long
float Float
double Double
72
Wrapper Classes - Cont.
  • Integer number new Integer(46)//Wrapping
  • Integer num new Integer(908)
  • Integer.MAX_VALUE // gives maximum integer
  • Integer.MIN_VALUE // gives minimum integer
  • Integer.parseInt(453) // returns 453
  • Integer.toString(653) // returns 653
  • number.equals(num) // returns false
  • int aNumber number.intValue() // aNumber is 46

73
Wrapper Classes Cont.
  • The Double wrapper class has equivalent methods
  • Double.MAX_VALUE // gives maximum double value
  • Double.MIN_VALUE // gives minimum double value
  • Double.parseDouble(0.45E-3) // returns 0.45E-3
  • parseDouble is only available in Java 2 and newer
    versions.
  • See the Java documentation for more on Wrapper
    classes.

74
String Class
  • Since Strings are Objects they can have methods.
  • String methods include
  • length()
  • equals(OtherString)
  • equalsIgnoreCase(OtherString)
  • toLowerCase()
  • toUpperCase()
  • trim()
  • charAt(Position)
  • substring(Start)
  • substring(Start, End)

75
String Class - Cont.
  • indexOf(SearchString)
  • replace(oldChar, newChar)
  • startsWith(PrefixString)
  • endsWith(SuffixString)
  • valueOf(integer)
  • Strings do not have any attributes.
  • See the API Docs for details on all the String
    class methods.

76
String Class - Cont.
  • Examples
  • int i
  • boolean aBool
  • String testStuff A testing string.
  • i testStuff.length() // i is 17
  • aBool testStuff.equals(a testing string.)
    // aBool is false
  • aBool testStuff.equalsIgnoreCase(A TESTING
    STRING.) // aBool is true

77
String Class - Cont.
  • char aChar
  • aChar testStuff.charAt(2) // aChar is t
  • i testStuff.indexOf(test) // i is 2

78
Aside - More about Strings
  • Is Hello class (a String literal) an Object?

Yup, Hello class!.length() would return 12.
  • Strings are actually stored as arrays of
    chars.
  • So, a String variable is actually just a pointer
    to an array in memory.
Write a Comment
User Comments (0)
About PowerShow.com