Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 5JA Introduction to Java Last Class We talked about how to pass in arguments from the command line. We talked about when data-types are sent to a method.

Similar presentations


Presentation on theme: "CS 5JA Introduction to Java Last Class We talked about how to pass in arguments from the command line. We talked about when data-types are sent to a method."— Presentation transcript:

1 CS 5JA Introduction to Java Last Class We talked about how to pass in arguments from the command line. We talked about when data-types are sent to a method they are either passed by reference or passed by value. We talked about how to read from and write text to a file. We talked briefly about exception handling (which is required when you open a file for reading or writing). We talked about how to parse text data from a file with the Scanner. We talked about how to format text to a file with a Formatter.

2 CS 5JA Introduction to Java This Class We’ll look at the built-in String library. We’ll look at the List interface and in particular the most common implementation of that interface, java.util.ArrayList.

3 CS 5JA Introduction to Java Strings We’ve already been using Strings extensively in this class (for printing, for labelling Accounts, etc). But there are some other useful things we can do with the String library. We can trim out whitespace: String s = “ space before and space after “; String trimmedString = s.trim(); We can change the case of the String: String lowerCaseString = “abc def”; String upperCaseString = lowerCaseString.toUpperCase();

4 CS 5JA Introduction to Java Strings And vice-versa: String upperCaseString = “ABCDEF”; String lowerCaseString = upperCaseString.toLowerCase(); We can determine the length of the String. String s = “I am 23 characters long”; System.out.println(“String s is “ + s.length() + “ characters long”);

5 CS 5JA Introduction to Java Strings We can split up the String into pieces based on a particular delimiter, or pattern: String duranDuranLyrics = “My_name_is_Rio”; String[] words = duranDuranLyrics.split(“_”); We can replace a sequence of letters with a new sequence: String misspelledString = “cieling”; String correctlySpelledString = misspelledString.replace(“ie”, “ei”);

6 CS 5JA Introduction to Java Strings We can make a new substring out of part of an original String: String longStr = “Blah blah blah important stuff blah blah blah”; String subStr = longStr.substring(15, 29); We can check to see if two string have the same data: String str1 = “abc”; String str2 = “abc”; boolean theSame = str1.equals(str2); String str1 = “abc”; String str2 = “abd”; boolean notTheSame = str1.equals(str2);

7 CS 5JA Introduction to Java Strings Take a close look at the Javadocs. There are some other powerful tools in the String library– mainly the ability to use regular expressions for string matching and substitution. http://java.sun.com/javase/6/docs/api/java/lang/String.html You can of course apply a sequence of operations to a String: String str = “ a b c d e f”; String newStr = str.trim().toUpperCase().substring(3,6).replace(“ “, “!”); But this can be a bit confusing... However, if you see code like this you will know how to read it– from left to right.

8 CS 5JA Introduction to Java Strings String str = “ a b c d e f”; String newStr = str.trim().toUpperCase().substring(3,6).replace(“ “, “!”); step 1: “a b c d e f” step 2: “A B C D E F” step 3: “ C D” step 4: “!C!D” step 5: assign “!C!D” to newStr.

9 CS 5JA Introduction to Java ArrayList Last week we talked about arrays, including multi-dimensional arrays. We made a note of a problem with arrays: you have to know their size before you work with them. For example, say we are reading lines of text from a file, and we want to store those lines in an array of Strings. But we don’t know how many lines there are! We have two choices: 1) We can loop through the list twice, once to count (so we can construct the array properly), and once to actually fill in the array. 2) We can make a super-big array and hope that the file isn’t bigger than we thought and that we don’t waste too much memory.

10 CS 5JA Introduction to Java ArrayList And actually we have another choice: 3) We can use an ArrayList to store the data. Here’s how you initialize an ArrayList to hold an arbitrary number of Strings: List listOfStrings = new ArrayList (); This syntax is a little bit unusual, and it was introduced into Java only a couple of years ago. The idea is that we have a bunch of different kinds of data structures, all of which are in some way a collection of data. And we have a framework (the Collections framework) for moving data into different data- structures.

11 CS 5JA Introduction to Java ArrayList List listOfStrings = new ArrayList (); The first word List is a special kind of data-type called an interface. We’ll talk about this in more detail later. The actual data-type is ArrayList, which is an implementation of the interface. An interface describes important features, but doesn’t actually provide the logic to do anything. The implementation of the interface is a normal class that is required to handle all of the important features. For example, if we have a list of data, we need to be able to add and remove data to it. All lists of data require these important features. But different types of lists might do it in different ways. We are using an ArrayList, which is very fast at “random access”, that is optimized for adding to, removing from, or getting or setting at data a particular location. Other lists are faster at iterating through data in order, etc.

12 CS 5JA Introduction to Java ArrayList List listOfStrings = new ArrayList (); The pointy braces explicitly defines the type of data that the List can hold. In this case, Strings and Strings only. Trying to add anything else to our listOfStrings will throw an error. So, to summarize: We have a List called listOfStrings which can only hold Strings and uses the ArrayList implementation to store and retrieve those Strings. Let’s look at the available methods in the List interface: (http://java.sun.com/javase/6/docs/api/java/util/List.html)

13 CS 5JA Introduction to Java ArrayList List listOfStrings = new ArrayList (); listOfStrings.add(“some words”); listOfStrings.add(4, “other words”); listOfStrings.remove(2); //remove String at 2 nd index (ie, the 3 rd String) listOfStrings.remove(“some words”); //find and remove the first occurance of the String (“some words”); listOfStrings.set(3, “yet another string”); //overwrite whatever is at index 3 and replace it with “yet another string”. String s = listOfStrings.get(2); //return the String that is at the 2 nd index. int pos = listOfStrings.indexOf(“some words”); //return index of “some words”) boolean doesStringExist = listOfStrings.contains(“some words”); int numStringsInList = listOfStrings.size();

14 CS 5JA Introduction to Java ArrayList As with normal Arrays, the most important things we do with Lists are : sorting, searching, and storing data. For arrays, we have a uitlity class called Arrays which has built in sorting and searching methods. Likewise, for Lists (and other types of data structures in the Collections Framework) we have a utility class called Collections with helpful static methods: Collections.sort(listOfStrings); //sorts alphabetically Collections.binarySearch(listOfStrings, “important stuff”); //returns index to “important stuff”

15 CS 5JA Introduction to Java ArrayList Additionally, there is some other cool stuff built in: Collections.rotate(listOfStrings, -3); Collections.shuffle(listOfStrings); Collections.reverse(listOfStrings); int numTimes = Collections.frquency(listOfStrings, “word”); int pos = Collections.min(listOfStrings); int pos = Collections.max(listOfStrings);

16 CS 5JA Introduction to Java Next Class New homework set will be on-line by this evening or tomorrow at latest. Will be due next Thursday and involve three or four problems. Next class: adding a mouseListener and a keyboardListener to a JFrame loading from and saving images to a file.

17 CS 5JA Introduction to Java MouseListener In the last assignment we learned how access the Graphics package to draw on a component, in our case we used the JPanel. If we want to use the mouse, we need to make use of a built-in interface called a MouseInputListener. This interface will provide information about the position of the mouse (in relationship to the JPanel) when it is mouse is moved, clicked, pressed, or dragged, and released. We talked briefly about interfaces last class. Java’s built-in interfaces may have some basic functionality, but you are required to implement certain functionality via specified methods. In the case of MouseInputListener we need to implement the following 7 methods: mouseClicked, mousePressed, mouseDragged, mouseReleased, mouseMoved, mouseEntered, and mouseExited.

18 CS 5JA Introduction to Java MouseListener Even if you only care about, say, what happens when the user clicks the mouse, but not what happens when the user moves it, you still need to provide that method. Otherwise the compiler will tell you that there is an error and that you haven’t fulfilled the contract designated by the interface. For instance, I have never used mouseEntered or mouseExited, and so I just provide empty functions for them like so: public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {}

19 CS 5JA Introduction to Java MouseListener However if you do care about the functionality, then you can make use of the MouseEvent it gives you to query the position of the mouse when that event is occurring. int mx = 0; int my = 0; public void mousePressed(MouseEvent me) { mx = me.getX(); my = me.getY(); System.out.printf(“mouse pressed at pixel position %d/%d\n”, mx, my); }

20 CS 5JA Introduction to Java MouseListener Let’s modify our PolkadotTest program so that it only draws polka dots at the places we specify with the mouse. Since we don’t know in advance how many times the user will press the mouse, we’ll use the ArrayList to store polkadots (instead of a normal array like we used before). During the paintComponent method we’ll iterate through our list of polkadots and draw them. [example code]

21 CS 5JA Introduction to Java MouseListener Now what if we mistakenly add a polka dot to the wrong place? Let’s modify our code so that a user can select a polkadot. If the user selects the polkadot it will be instantly removed from the list, and thus won’t be drawn anymore. [example code]

22 CS 5JA Introduction to Java MouseListener As a final example, instead of making the user remove and re-add a polkadot, we’ll let the user drag it to a new position. [example code]

23 CS 5JA Introduction to Java MouseListener As a final final example, let’s make a new program that imitates the pencil tool from Photoshop. It draws a small black square under the mouse as we press and drag the mouse across the screen. [example code]

24 CS 5JA Introduction to Java KeyListener Just as there are built-in listeners to get mouse events, there is a built-in listener to get keyboard events. We also need to tell the compiler that our class implements the interface, and when we instantiate the object we need to add the listener to our new object. We also need to make sure and actually implement all the methods that the interface defines.

25 CS 5JA Introduction to Java KeyListener adding listeners, setting focus fonts saving images switch statement try/catch with imageIO difference between interface and extends this keyword

26 CS 5JA Introduction to Java Arrays We get at the data in the array using the indexing notation: int checkNumber = myNumbers[0]; int checkNumber = myNumbers[55]; etc...

27 CS 5JA Introduction to Java Arrays what’s going on in these code snippets? int[] myIntArray = new int[3]; System.out.println(“num = “ + myIntArray[1]); int[] myIntArray = new int[3]; myIntArray[0] = 99; myIntArray[1] = 98; myIntArray[2] = 97; myIntArray[3] = 96; double[] myDblArray = new double[2]; myDblArray[0] = 99.9; myDblArray[1] = -100.0; System.out.println(“num = “ + myIntArray[2]);

28 CS 5JA Introduction to Java Arrays int[] myIntArray = new int[3]; myIntArray[0] = 2; myIntArray[1] = 0; myIntArray[2] = 1; myIntArray[3] = 17; what does myIntArray[2] equal? what does myIntArray[myIntArray[0]] equal? what does myIntArray[myIntArray[0] – myIntArray[2]] equal?

29 CS 5JA Introduction to Java Arrays You can create, initialize, and fill an array all at the same time with this shortcut syntax: String[] myStrArray = {“Duck”, “Duck”, “Duck”, “Goose”}; boolean[] myBoolArray= {false, false, false, true}; what is myStrArray[1] contain? what does x equal? boolean x = myBoolArray[0]; what does x equal? boolean x = myBoolArray[4]; what does str equal? boolean str = myStrArray[3];

30 CS 5JA Introduction to Java Arrays String[] grades = {“A”, “A+”, “C”, “F”, “B+”}; How do I change the grade from a C to an A?

31 CS 5JA Introduction to Java Arrays String[] grades = {“A”, “A+”, “C”, “F”, “B+”}; How do I change the grade from a C to an A? grades[2] = “A”; Or something like: String newGrade = “A”; grades[2] = newGrade;

32 CS 5JA Introduction to Java Arrays What are arrays good for? An array is a simple data structure. That is, you have a set of data and you give it some structure. I used the example of a pile of papers that you put into a filing cabinet. The main things you can do with your filing cabinet: storing information, sorting information and searching for information [see example program, ArraysTest.java]

33 CS 5JA Introduction to Java Arrays You can also pass arrays to methods just like other data types: This sample shows how to use one of the binarySearch methods in the Arrays library. public Test() { int[] someArray = {2, 4, 1, -4, 5, 6}; boolean hasZero = doesListContainAZero(someArray); } public boolean doesListContainAZero(int[] intArray) { if (Arrays.binarySearch(intArray, 0) > -1) { return true; } return false; }

34 CS 5JA Introduction to Java Pass-by-value vs Pass-by-reference In Java, when you pass a variable to a method it either a) makes a new variable which is a copy of the original value, even if the variable has the same name. b) passes in the exact same data, even if the variable is given a different name. The first possibility is called “passing-by-value” and it is what happens for any primitive data types (ints, booleans, doubles, etc). Every other data type in Java uses “passing-by-reference”. This includes every object and arrays.

35 CS 5JA Introduction to Java Pass-by-value vs Pass-by-reference When something is passed-by-reference, it means that any modification to the data within a method will affect the data outside the method as well. When something is passed-by-value, it means that any modification to the data within the method has no affect whatsoever on the data outside the method. public void method1() { int x = 5; method2(x); System.out.println(“x = “ + x); //what is x? } public void method2(int x) { x = 6; }

36 CS 5JA Introduction to Java Pass-by-value vs Pass-by-reference Arrays are passed-by-reference public void method1() { int[] arr = {5, 6, 7}; method2(arr); //what is arr[0]? System.out.println(“arr[0] = “ + arr[0]); } public void method2(int[] aNewArray) //not really new! { aNewArray[0] = 1001; }

37 CS 5JA Introduction to Java Pass-by-value vs Pass-by-reference Primitive values in arrays are still passed-by-value public void method1() { int[] arr = {5, 6, 7}; method2(arr[0]); //just an int! //what is arr[0]? System.out.println(“arr[0] = “ + arr[0]); } public void method2(int aNewInt) //it really is new! { aNewInt = 1001; }

38 CS 5JA Introduction to Java Multi-dimensional Arrays You can also make an array of arrays, also called a Multi-dimensional array. For instance, to declare a two-dimensional int array, you can do this: int[][] da = new int[2][]; da[0] = new int[] {5,4,3,2,1}; da[1] = new int[2]; da[1][0] = 100; da[1][1] = 99; So what’s in da[0]? What’s in da[1]? What value is da[0][2]? What value is da[1][3]? What value is da[1][1]? What happens if you print d[0] or d[1]?

39 CS 5JA Introduction to Java Multi-dimensional Arrays You can also use the shortcut method for multidimensional arrays: int da[][] = { {1, 2, 3}, {10, 11, 12} }; [see ArraysTest.java] You can have as high a dimension as you want... [see ArraysTest.java]

40 CS 5JA Introduction to Java Multi-dimensional Arrays Main issue with arrays... You have to know their size before you work with them. You can’t arbitrarily add extra data into them without recreating them from scratch. The more flexible way is to use the List interface... which we’ll talk about another time.

41 CS 5JA Introduction to Java Quick note about debugging... If your program doesn’t compile, then you have a syntax error. The compiler will provide you with a list of errors and line numbers for where each error occurs. Sometimes it’s a little off. The error might be that you forgot a semi-colon on a line, but the line that shows up as an error is the line below. To the compiler, the error doesn’t really happen until it runs into something it can’t handle, which in this case is when all of sudden there is something unexpected. System.out.print(“hello”) System.out.print(“again”); The compiler removes all whitespace (except within quotes) so it sees something like this... System.out.print(“hello”)System.out.print(“again”); So it finds the error at the capital S at the beginning of line 2.

42 CS 5JA Introduction to Java Quick note about debugging... If your program compiles but gives you unexpected results, then you have a logical error. You will have no information about why it isn’t doing what you wanted it to! There are tools called debuggers which you can attach to your program and step through code so you can tell what’s going on at every point. But usually the simplest solution is to break things into small steps and make sure that each of those steps work. For instance, you can take a complicated piece of code and break it up into smaller methods, and then write test cases to make sure that the individual methods are doing what they are supposed to.

43 CS 5JA Introduction to Java Quick note about debugging... The main thing though to remember is that System.out.println is your friend. You can use it to make sure that your code has gotten to a certain place. You can use it to make sure that you have the right values at particular variables public void myMethod(int a, int b) { System.out.println(“in myMethod, int a = “ + a); System.out.println(“int b = “ + b); int c = complicatedFunction(a, b); System.out.println(“ok, c = “ + c); }

44 CS 5JA Introduction to Java Passing in arguments from the command line We’ve talked about the main mathod signature: public static void main (String args[]) What does the String args[] part do? It says that the method expects an array of type String. Built in to Java is the ability to pass Strings in from the command line, like so: java MyProgram str0 str1 str2 In the main method you can access these Strings:

45 CS 5JA Introduction to Java Passing in arguments from the command line public static void main (String args[]) { for (int i = 0; i < args.length; i++) { System.out.println(“args[“+i+”] = “ + args[i]); } You can use these arguments to pass in parameters, filenames, numbers, etc. But as you can see, by default they are Strings, so you need to convert them to other data types if necessary.

46 CS 5JA Introduction to Java Parsing data from a String Commonly, you’ll want to get a number out of a String. If a user passes in the string “5”, you will want to convert it to an int so that you can do something with it. There are different ways to do this. Because it is so common, there is a built-in utility method in the Integer class which lets you parse out a number: int num = Integer.parseInt(“5”); String numApples = “I have 5 apples”; int num = Integer.parseInt(numApples);

47 CS 5JA Introduction to Java Parsing data from a String For more complex parsing, you can use the Scanner as we have already done. String numApples(“I have 10 apples!”); Scanner s = new Scanner(numApples); while(s.hasNext()) { if(s.hasNextInt()) { int num = s.nextInt(); } If you try to scan for a data type that isn’t there you will get an Exception, in this case a InputMismatchException.

48 CS 5JA Introduction to Java Exceptions Exception handling is the term used for dealing with errors. So far, we have assumed that if there are any errors then they are “fatal”. We either explicitly exit the program immediately, or we let the Java exit the program when it discovers a run-time error. However there are many cases when we might not want to exit the program when there is an error, or make sure that we haven’t left any resources open (ie databases, files, usb devices, etc), or at the very least print the reason why there is a problem before exiting. We can do this by using the exception handler to “catch” the error.

49 CS 5JA Introduction to Java Exceptions Certain objects will throw errors when something inappropriate happens. So we can wrap code in a try-catch block to try and make sure the code works, and if not, catch the error and then decide what to do. Scanner s = new Scanner(System.in); while(s.hasNext()) { int num = s.nextInt(); } If a user types letters instead of number, the Scanner method will throw a run-time error, and the program will exit and print an error message to the screen.

50 CS 5JA Introduction to Java Exceptions But if we wrap it in a try-catch block, then we can stop the code from exiting and decide if it’s really a problem or not. Scanner s = new Scanner(System.in); try { while(s.hasNext()) { int num = s.nextInt(); } catch (InputMismatchException ime) { System.out.println(“hey– you did something wrong! But no worries!”); } You can look to see what errors might be thrown by a method by looking at the JavaDocs

51 CS 5JA Introduction to Java Exceptions public int nextInt()  Scans the next token of the input as an int. Returns: the int scanned from the input  Throws: InputMismatchException - if the next token does not match the Integer regular expression, or is out of range InputMismatchException NoSuchElementException - if input is exhausted NoSuchElementException IllegalStateException - if this scanner is closed IllegalStateException

52 CS 5JA Introduction to Java Exceptions Some methods require that you catch the errors. Someone asked about pausing the program. Since pausing the program basically creates a new temporary process which can potentially be interrupted (we don’t need to get into the details of threading right now), we are required to wrap it in a try-catch block. try { Thread.sleep(1000); //pause for 1000 milliseconds, or 1 second } catch(InterruptedException ie) { System.out.println(“just to let you know, we didn’t actually sleep for 1 second because we were interrupted!”); }

53 CS 5JA Introduction to Java Exceptions Another example: if you try to use a file ten you are required to wrap it in a try-catch block in order to handle the possibility that the file doesn’t actually exist. File file = new File(“text.txt”); Scanner scanner = null; try { // Create a scanner to read the file scanner = new Scanner (file); } catch (FileNotFoundException e) { System.out.println ("File not found!"); // Stop program if no file found System.exit (0); // or we could force the user to entire a new filename, or browse for the file, etc } And this is the main reason I’m introducing this now, because your homework will require that you read from and write to a file.

54 CS 5JA Introduction to Java Reading from a file There are different ways to read from a file. But this one makes it especially easy to read text from a file. Others are better for images, etc. We’ve used the Scanner to read text from the command prompt, but it can also be used to read from a file. First, create a File object with a filename: File file = new File(“myTextFile.txt”); Then make a Scanner that scans from that file: Scanner fileScanner = new Scanner(file);

55 CS 5JA Introduction to Java Exceptions Since this particular constructor explicitly throws an exception, we just need to wrap it in the appropriate try-catch block Scanner fileScanner; try { fileScanner = new Scanner(file); } catch (FileNotFoundException e) { //handle error in some way... }

56 CS 5JA Introduction to Java Parsing text from a file Now we can use the normal Scanner operations to put the contents of the file into variables that we can use in our program. Here’s a file called “grades.txt”: 87 99 12 80 100

57 CS 5JA Introduction to Java Parsing text from a file Scanner fileScanner; try { fileScanner = new Scanner(“grades.txt”); } catch (FileNotFoundException e) { System.out.exit(0); } int[] grades = new int[5]; for(int i = 0; i < 5; i++) { grades[i] = fileScanner.nextInt(); }

58 CS 5JA Introduction to Java Writing text to a file The opposite of reading text to a file is writing text to a file. Java has a simple method for formatting data to a String, the terminal, or to a file. It uses the same conventions as the “printf” command you may have seen in the textbook. It interprets special codes as particular data types, these are the only ones we’ll be concerned with %d = number (int or long) %s = string %f = decimal (float or double) int temperature = 55; System.out.printf(“It is %d degrees out today\n”, temperature);

59 CS 5JA Introduction to Java Writing text to a file File file = new File(filename); Formatter formatter = null; try { formatter = new Formatter (file); } catch (FileNotFoundException e) { //not a problem because we are about to create the file!!! } for(int i = 0; i < grades.length; i++) { formatter.format (“Grade for student %d is %d\n”, i, grades[i]); } //need to “flush” the data to the file, then close the file. formatter.flush (); formatter.close ();


Download ppt "CS 5JA Introduction to Java Last Class We talked about how to pass in arguments from the command line. We talked about when data-types are sent to a method."

Similar presentations


Ads by Google