html5-img
1 / 52

Java Workshop Part #2

Java Workshop Part #2. Collection of Data and Abstract Data Type (ADT). Objectives. Useful Java Classes Learn about wrapper classes, String, DecimalFormat , Random Collection of Data Learn to write programs using arrays Learn to use generics and ArrayList class Abstract Data Type

maddox
Télécharger la présentation

Java Workshop Part #2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Workshop Part #2 Collection of Data and Abstract Data Type (ADT)

  2. Objectives • Useful Java Classes • Learn about wrapper classes, String, DecimalFormat, Random • Collection of Data • Learn to write programs using arrays • Learn to use generics and ArrayListclass • Abstract Data Type • Learn about data abstraction • Learn to use Java Interface to define an ADT • Exception Handling • Learn about exception indication / handling mechanism Introductory Java Workshop - Part II

  3. 1. Wrapper classes (1/2) • These are called wrapper classes – each corresponding to each primitive data type • Types such as int, float, double, char, boolean, etc. are primitive data types. • They are not objects. They are legacies of older languages. • Sometimes we need object equivalent of these primitive data types [CS1020 Lecture 2 AY2012/3 S2]

  4. 1. Wrapper classes (2/2) int i = 9; Integer y = new Integer(i); System.out.println("i = " + i); System.out.println("Value in y = " + y.intValue()); intnum = Integer.valueOf("28"); // num contains 28 String str= Integer.toString(567); // str contains "567" We may convert a primitive type value to its corresponding object. For example, between int and Integer: We may use methods in the wrapper classes to perform conversion between types. For example, conversion between string and integer: Look up the API documentation and explore the wrapper classes on your own [CS1020 Lecture 2 AY2012/3 S2]

  5. 1. Autoboxing/unboxing • Converting an object of a wrapper type (e.g.: Integer) to its corresponding primitive (e.g: int) value is called unboxing. • The Java compiler applies unboxing when an object of a wrapper class is: • Passed as a parameter to a method that expects a value of the corresponding primitive type • Assigned to a variable of the corresponding primitive type int i = new Integer(5); // unboxing Integer intObj = 7; // autoboxing System.out.println("i = " + i); System.out.println("intObj = " + intObj); i = 5 intObj = 7 int a = 10; Integer b = 10; // autoboxing System.out.println(a==b); true Introductory Java Workshop - Part II

  6. 2. The String class (1/2) • API: • http://docs.oracle.com/javase/7/docs/api/java/lang/String.html • Creating String objects • String text = new String("Good morning!"); • String text = "Good morning!"; • Useful String functions [CS1020 Lecture 2 AY2012/3 S2]

  7. 2. The String class (2/2) TestString.java classTestString { public static void main(String[] args) { String text = new String("I'm studying CS1020."); System.out.println("text: " + text); System.out.println("text.length() = " + text.length()); System.out.println("text.substring(5,8) = " + text.substring(5,8)); String newText = text + "How about you?"; System.out.println("newText: " + newText); if (text.equals(newText)) System.out.println("text and newText are equal."); else System.out.println("text and newText are not equal."); text: I'm studying CS1020. text.length() = 20 text.substring(5,8) = tud newText: I'm studying CS1020.How about you? text and newText are not equal. [CS1020 Lecture 2 AY2012/3 S2]

  8. 3. DecimalFormat • An alternative for printf() Introductory Java Workshop - Part II

  9. 3. DecimalFormat: Example TestDecimalFormat.java import java.text.DecimalFormat; classTestDecimalFormat { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("0.000"); // 3 dec. pl. System.out.println("PI = " + df.format(Math.PI)); } } Math.PI = 3.142 • Note that df.format(x) does not change the value in x. It merely displays the value in x in the specified format. • Explore the API documentation for more details. Introductory Java Workshop - Part II

  10. 4. Random class Alternative: Math.random() Introductory Java Workshop - Part II • There is a Random class • import java.util.Random; • Constructors • Random(): random numbers generated are different each time program is run • Random(long seed): random numbers generated are taken from a pre-determined fixed sequence based on the seed • Useful method: • intnextInt(int n): generate a random integer in [0, n). • intnextDouble(): return a random real number in [0, 1).

  11. 4. Generating random numbers TestRandom.java import java.util.Random; classTestRandom { public static void main(String[] args) { // To generate a random integer in [51,70] Random rnd = new Random(); int num1 = rnd.nextInt(20) + 51; System.out.println("num1 = " + num1); int num2 = (int) (Math.random() * 20) + 51; System.out.println("num2 = " + num2); } } Introductory Java Workshop - Part II

  12. 5. Array A 24 7 -3 15 9 A[0] A[1] A[2] A[3] A[4] • Array is the simplest way to store a collection of data of the same type (homogeneous) • It stores its elements in contiguous memory • Array index begins from zero • Example of a 5-element integer array A with elements filled Introductory Java Workshop - Part II

  13. 5. Array in Java (1/2) TestArray1.java class TestArray1 { public static void main(String[] args) { int[] arr; // arr is a reference // create a new integer array with 3 elements // arr now refers (points) to this new array arr = newint[3]; // using the length attribute System.out.println("Length = " + arr.length); arr[0] = 100; arr[1] = arr[0] - 37; arr[2] = arr[1] / 2; for (int i=0; i<arr.length; i++) System.out.println("arr[" + i + "] = " + arr[i]); } } Declaring an array: datatype[] array_name Constructing an array: array_name = newdatatype[size] Obtaining the size of an array Length = 3 arr[0] = 100 arr[1] = 63 arr[2] = 31 Accessing individual array elements In Java, array is an object. Every array has a length attribute which is public Introductory Java Workshop - Part II

  14. 5. Array in Java (2/2) TestArray2.java class TestArray2 { public static void main(String[] args) { // Construct and initialise array double[] arr = { 35.1, 21, 57.7, 18.3 }; // using the length attribute System.out.println("Length = " + arr.length); for (int i=0; i<arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); // Alternative way for (double element: arr) { System.out.print(element + " "); } System.out.println(); System.out.println(Arrays.toString(arr)); } } Length = 4 35.1 21.0 57.7 18.3 35.1 21.0 57.7 18.3 [35.1, 21.0, 57.7, 18.3] Syntax (enhanced for-loop): for (datatypee: array_name) Go through all elements in the array. “e” automatically refers to the array element sequentially in each iteration Using toString() method in Arrays class Alternative loop syntax for accessing array elements Illustrate toString() method in Arrays class to print an array Introductory Java Workshop - Part II

  15. 5. Array: As a parameter TestArray3.java class TestArray3 { public static void main(String[] args) { int[] list = { 22, 55, 33 }; swap(list, 0, 2); for (int element: list) System.out.print(element + " "); System.out.println(); } // To swap arr[i] with arr[j] public static void swap(int[] arr, inti, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } 33 55 22 Parameter type: datatype[] • The reference to the array is passed into a method: • Any modification of the elements in the method will affect the actual array Introductory Java Workshop - Part II

  16. 5. Array: As a return type TestArray4.java class TestArray4 { public static void main(String[] args) { double[] values; values = makeArray(5, 999.0); for (double value: values) { System.out.println(value + ""); } } // To create an array and return it to caller public static double[] makeArray(int size, double limit) { double[] arr = new double[size]; for (int i=0; i < arr.length; i++) arr[i] = limit/(i+1); return arr; } } 999.0 499.5 333.0 249.75 199.8 Return type: datatype[] Array can be returned from a method Introductory Java Workshop - Part II

  17. 6. Ex #1: Missing Digits Enter a number: 73015 Missing digits in 73015: 2 4 6 8 9 • To explore: What is the default value of an element in a boolean array? [This is adapted from a CS1010 exercise in C] Write a program MissingDigits.java to read in a positive integer and list out all the digits that do not appear in the input number. You should use a boolean array. Example: Introductory Java Workshop - Part II

  18. 6. Ex #1: Missing Digits missingDigits.c #include <stdio.h> // Function prototypes omitted for brevity intmain(void) { intnumber; intfound[10] = {0}; // found[i] = 0 means digit i is missing printf("Enter a number: "); scanf("%d", &number); analyseNumber(number, found); printf("Missing digits in %d: ", number); printMissingDigits(found); return0; } voidanalyseNumber(intnum, intfoundArr[]) { intdigit; while(num > 0) { digit = num%10; foundArr[digit] = 1; // found digit in input number num/= 10; } } Introductory Java Workshop - Part II

  19. 6. Ex #1: Missing Digits missingDigits.c … void printMissingDigits(intfoundArr[]) { inti; for (i = 0; i < 10; i++) { if (!foundArr[i]) printf("%d ", i); } printf("\n"); } } Introductory Java Workshop - Part II

  20. 6. Ex #1: Missing Digits MissingDigits.java importjava.util.*; classMissingDigits { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int number = sc.nextInt(); boolean[] found = analyseNumber(number); System.out.print("Missing digits in " + number + ": "); printMissingDigits(number, found); } public static boolean[] analyseNumber(intnumber){ boolean[] found = new boolean[10]; for (inti=0; i<found.length; i++) found[i] = false; while (number > 0) { found[number%10] = true; number /= 10; } return found; }  Introductory Java Workshop - Part II

  21. 6. Ex #1: Missing Digits MissingDigits.java public static voidprintMissingDigits(boolean[] found){ for (int i=0; i<found.length; i++) { if (!found[i]) System.out.print(i + " "); } System.out.println(); } }  Introductory Java Workshop - Part II

  22. 7. Array: Common Mistakes (1/2) public static void main(String[] args) { int[] numbers = new int[10]; . . . for (int i = 1; i <= numbers.length; i++) System.out.println(numbers[i]); } • To obtain the length (size) of an array, we use the length attribute • Example: arr.length • Do NOT write arr.length() • Array index out of range • Beware of ArrayIndexOutOfBoundsException Introductory Java Workshop - Part II

  23. array null null null 15 15 15 Corrected code: array 10 10 10 radius radius radius Point[] array = newBall[3]; for (int i=0; i<array.length; i++) { array[i] = newBall(); array[i].setRadius(15); } 7. Array: Common Mistakes (2/2) Ball[] array = new Ball[3]; for (int i=0; i<array.length; i++) { array[i].setRadius(15); } There are no objects referred to by array[0], array[1], and array[2], so how to setLocation() on them?! Introductory Java Workshop - Part II Remember to initialize the array!

  24. 7. Array: Drawback • Array has one major drawback: • Once initialized, the array size is fixed • Reconstruction is required if the array size changes • To overcome such limitation, we can use some classes related to array • We will be using ArrayListin CS1020 • Other alternatives include Arrayand Vector Introductory Java Workshop - Part II

  25. 8. ArrayList Introductory Java Workshop - Part II • Features of ArrayList • Dynamic size: expands or shrinks automatically • Generic: allows any reference data types • Creating ArrayList objects • ArrayList<Integer> list = new ArrayList<Integer>(); • ArrayList<String> list = new ArrayList<String>(); • … • Useful methods

  26. 8. ArrayList: Example TestArrayList.java importjava.util.ArrayList; import java.util.Scanner; classTestArrayList { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<Integer> list = new ArrayList<Integer>(); System.out.println("Enter a list of integers, press ctrl-d to end."); while (sc.hasNext()) { list.add(sc.nextInt()); } System.out.println(list); // using ArrayList's toString() // Move first value to last list.add(list.remove(0)); System.out.println(list); } } Output: Enter a list ... to end. 31 17 -5 26 50 (user press ctrl-d here) [31, 17, -5, 26, 50] [17, -5, 26, 50, 31] Introductory Java Workshop - Part II

  27. 9. Ex #2: Detecting Duplicates Output: Enter a list of integers, press ctrl-d to end. 1 2 3 4 3 2 1 (user press ctrl-d here) List: [1, 2, 3, 4] Duplicates detected: 3 Write a program DetectDuplicates.java to read in integer values until ctrl-d is entered. You are to keep track of the unique values and count how many duplicates were detected. Sample Run: Introductory Java Workshop - Part II

  28. 9. Ex #2: Detecting Duplicates importjava.util.*; classDetectDuplicates { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<Integer> list = newArrayList<Integer>(); intcountDuplicates= 0, num; System.out.println("Enter a list of integers, press ctrl-d to end."); while(sc.hasNext()) { num= sc.nextInt(); if (list.contains(num)) { countDuplicates++; } else { list.add(num); } } System.out.println("List: " + list); System.out.println("Duplicates detected: " + countDuplicates); } }  Introductory Java Workshop - Part II

  29. 10. Abstract Data Type (ADT) (1/3) • ADT is a collection of data together with a specification of a set of operations on that collection of data • Specifications indicate what ADT operations do, but not how to implement them • When a program needs data operations that are not directly supported by a language, you need to create your own ADT • You should first design the ADT by carefully specifying the operations before implementation Introductory Java Workshop - Part II

  30. 10. Abstract Data Type (ADT) (2/3) • Data: water • Operations: chill, crush, cube, and isEmpty • Data structure: the internal structure of the dispenser • Walls: made of steel The only slits in the walls: • Input: water • Output: chilled water, crushed ice, or ice cubes. Crushed ice can be made in many different ways. We don’t care how it was made • Example: A water dispenser as an ADT Introductory Java Workshop - Part II

  31. 10. Abstract Data Type (ADT) (3/3) • A WALL of ADT operations isolates a data structure from the program that uses it • An interface is what a program/module/class should understand on using the ADT Introductory Java Workshop - Part II

  32. 10. Java Interface • Java interfaces provide a way to specify common behaviour for a set of (possibly unrelated) classes • Java interface can be used for ADT • It allows further abstraction/generalization • It uses the keyword interface, rather than class • It specifies methods to be implemented • A Java interface is a group of related methods with empty bodies • It can have constant definitions (which are implicitly public static final) • A class is said to implement the interface if it provides implementations for ALL the methods in the interface Introductory Java Workshop - Part II

  33. 11. Example: Complex Number ADT We will leave out divide Note: add means to return the result of add another complex number to 'this' complex number. Likewise for times and minus. User-defined data types can also be organized as ADTs Let’s create a “Complex” ADT for complex numbers Introductory Java Workshop - Part II

  34. 11. Example: Complex Number ADT • E.g. Complex ADT interface ComplexI.java publicinterfaceComplexI { publicdoublegetReal(); // returns this.real publicdoublegetImag(); // returns this.imag publicvoidsetReal(double real); // set this.real publicvoidsetImag(doubleimag); // set this.imag publicComplexIadd(ComplexI c); // return this + c publicComplexI minus(ComplexI c); // return this - c publicComplexItimes(ComplexI c); // return this * c } • In interface, methods have signatures (headers) but no implementation Introductory Java Workshop - Part II

  35. 12. Ex #3: Fraction as ADT (1/2) • Qn: Whatare the data members (attributes) of a fraction object (without going into its implementation)? • Qn: Whatare the behaviours (methods) you want to provide for this class (without going into its implementation)? We will leave out divide for the moment  We are going to view Fraction as an ADT, before we proceed to implement Fraction Introductory Java Workshop - Part II

  36. 12. Ex #3: Fraction as ADT (2/2) FractionI.java publicinterface FractionI { publicint getNumer(); // return numerator part publicint getDenom(); // return denominator part publicvoidsetNumer(intnumer); // set new numerator publicvoidsetDenom(intdenom); // set new denominator publicFractionIadd(FractionI f); // return this + f publicFractionI minus(FractionI f); // return this - f publicFractionItimes(FractionI f); // return this * f } • How do we write an Interface for Fraction? Let’s call it FractionI • You may refer to interface ComplexI for idea Introductory Java Workshop - Part II

  37. 13.ComplexI Implementation (1/2) ComplexCart.java class ComplexCart implementsComplexI { private double real; private double imag; // Constructor public ComplexCart(double r, double i) { real = r; imag = i; } // Accessors publicdoublegetReal() { return this.real; } publicdoublegetImag() { return this.imag; } // Mutators public void setReal(double real){ this.real= real; } public void setImag(double imag){ this.imag= imag; } // Overriding methods public String toString() { if (imag == 0) return (real + ""); else if (imag < 0) return (real + "" + imag + "i"); else return (real + "+" + imag + "i"); } Introductory Java Workshop - Part II

  38. 13.ComplexI Implementation (2/2) ComplexCart.java public ComplexIadd(ComplexIc) { doublenewReal = real + c.getReal(); doublenewImag = imag+ c.getImag(); return new ComplexCart(newReal, newImag); } public ComplexIminus(ComplexIc) { doublenewReal = real -c.getReal(); doublenewImag = imag- c.getImag(); return new ComplexCart(newReal, newImag); } public ComplexItimes(ComplexIc) { doublenewReal= real * c.getReal() – imag * c.getImag(); doublenewImag= real * c.getReal() + imag * c.getReal(); return new ComplexCart(newReal, newImag); } } (x + yi)(u + vi) = (xu – yv) + (xv + yu)i. Introductory Java Workshop - Part II

  39. 13. Testing Complex class TestComplex.java class TestComplex { public static void main(String[] args) { // Testing ComplexCart ComplexI a = new ComplexCart(10.0, 12.0); ComplexI b = new ComplexCart(1.0, 2.0); System.out.println("Testing ComplexCart:"); System.out.println("a+b is " + a.add(b)); System.out.println("a-b is " + a.minus(b)); System.out.println("a*b is " + a.times(b)); Testing ComplexCart: a+b is 11.0+14.0i a-b is 9.0+10.0i a*b is -14.0+22.0i Introductory Java Workshop - Part II

  40. 14. Ex #4: FractionI Implementation (1/3) Fraction.java class Fraction implements FractionI { // Data members private int numer; private int denom; // Constructors public Fraction() { this(1,1); } public Fraction(int numer, int denom) { setNumer(numer); setDenom(denom); } // Accessors (required by FractionI) publicint getNumer() { return numer; } publicint getDenom() { return denom; } // Mutators (required by FractionI) publicvoid setNumer(int numer) { this.numer = numer; } publicvoid setDenom(int denom) { this.denom = denom; }  Implement the Fraction ADT using 2 integer data members for numerator and denominator Introductory Java Workshop - Part II

  41. 14. Ex #4: FractionI Implementation (2/3) Fraction.java // Return this + f public FractionI add(FractionI f) { int numer = (this.getNumer() * f.getDenom()) + (f.getNumer() * this.getDenom()); int denom = this.getDenom() * f.getDenom(); FractionI ans = new Fraction(numer, denom); returnans; } // minus() is similar to add and hence omitted // Return this * f public FractionI times(FractionI f) { intnumer = this.getNumer() * f.getNumer(); intdenom = this.getDenom() * f.getDenom(); FractionIans = new Fraction(numer, denom); returnans; }  Introductory Java Workshop - Part II

  42. 14. Ex #4: FractionI Implementation (3/3) Fraction.java // Overriding toString() method public String toString() { returnthis.getNumer() + "/" + this.getDenom(); } } Enter 1st fraction: 1 2 Enter 2nd fraction: 3 4 1st fraction is 1/2 2nd fraction is 3/4 Sum is 10/8 Difference is -2/8 Product is 3/8 Run the given TestFraction.java program to test out the Fraction class.  Introductory Java Workshop - Part II

  43. 15. Exception Introductory Java Workshop - Part II • Many errors may occur during program execution • Method for factorial computation called with a negative number • Running out of memory when executing a method on an input • Java provides the exception mechanism: • Indicate an error (exception event) has occurred • Let the user decide how to handle the problem in a separate section of code specific for that purpose • Crash the program if the error is not handled • Exception mechanism consists of two components: • Exception indication • Exception handling

  44. 15. Exception Indication: Syntax (1/2) SYNTAX throw ExceptionObject; • Exception object must be: • An object of a class derived from class Throwable • Contain useful information about the error • There are a number of useful predefined exception classes: • ArithmeticException • NullPointerException • IndexOutOfBoundsException • IllegalArgumentException Introductory Java Workshop - Part II • To indicate an error is detected: • Also known as throwing an exception • This allows the user to detect and handle the error

  45. 15. Exception Indication: Syntax (2/2) Introductory Java Workshop - Part II • The different exception classes are used to categorize the type of error: • There is no major difference in the available methods

  46. 15. Exception Indication: Example public static int factorial(int n) throws IllegalArgumentException { if (n < 0) { thrownew IllegalArgumentException(n + " is invalid!"); } int ans = 1; for (int i = 2; i <= n; i++) ans *= i; return ans; } This declares that method factorial() may throw IllegalArgumentException This creates an exception object and throws it Introductory Java Workshop - Part II

  47. 15. Exception Handling: Syntax try { statement(s);} // try block// exceptions might be thrown catch (ExpClass1 obj1) {statement(s); } catch (ExpClass2 obj2) { statement(s);} // one or more catchblock// Do something about the exception finally { statement(s); } // finallyblock – for cleanup code // optional Introductory Java Workshop - Part II • As the user of a method that can throw exception(s): • It is your responsibility to handle the exception(s) • Also known as exception catching

  48. 15. Exception Handling: Example class TestException { public static int factorial(int n) throws IllegalArgumentException { //code not shown } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter n: "); int input = sc.nextInt(); try { System.out.println("Ans = " + factorial(input)); } catch (IllegalArgumentException expObj) { System.out.println(expObj.getMessage()); } } } We choose to print out the error message in this case. There are other ways to handle this error. Introductory Java Workshop - Part II

  49. 16. Ex #5: Exceptions FractionI.java publicinterface FractionI { publicint getNumer(); //returns numerator part publicint getDenom(); //returns denominator part publicvoidsetNumer(intnumer); //sets new numerator publicvoidsetDenom(intdenom); //sets new denominator publicFractionIadd(FractionI f); //returns this + f publicFractionI minus(FractionI f); //returns this - f publicFractionItimes(FractionI f); //returns this * f publicFractionIdivide(FractionI f); //returns this / f }  We are to include a divide(FractionI f) method in the FractionI interface, and implement it in Fraction.java to compute and return the division of two fractions. What if the fraction f is zero? Then we have a division by zero operation which is illegal. Use exception to handle such an error. Introductory Java Workshop - Part II

  50. 16. Ex #5: Exceptions Fraction.java // Only divide() method is shown here // Return this / f public FractionI divide(FractionI f){ int numer = this.getNumer() * f.getDenom(); int denom = this.getDenom() * f.getNumer(); try { if (denom == 0) { // a division-by-zero-error occurs throw new ArithmeticException("Division by zero error!"); } } catch (ArithmeticException e) { System.out.println(e.getMessage()); System.exit(1); } FractionI ans = new Fraction(numer, denom); returnans; }  Introductory Java Workshop - Part II

More Related