Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 14 CS202. JUnit on the Final The programming questions on the Sample and actual final exams will require you to write Junit tests. Be sure to.

Similar presentations


Presentation on theme: "Lecture 14 CS202. JUnit on the Final The programming questions on the Sample and actual final exams will require you to write Junit tests. Be sure to."— Presentation transcript:

1 Lecture 14 CS202

2 JUnit on the Final The programming questions on the Sample and actual final exams will require you to write Junit tests. Be sure to consider my JUnit examples from the lecture notes and the tests I provided in the Rectangle sorting lab Write a simple class with testable methods and practice creating JUnit tests.

3 Binary File I/O Real world applications usually use databases to store large amounts of information – Main exceptions are apps that have unique file formats that can’t easily be translated to databases, like word processors or paint software. We have already discussed text file i/o, which uses plain text files. These can be read using a text editor. There is a very nice way to store data from OOP applications directly to disk, though: binary file i/o Binary files store data as sequences of bytes in a format that is usually far more compact than text files. If you open a binary file in a word processor or text editor, you will see gibberish Every application formats its binary files differently. The only way to easily retrieve the data is by using an application that can parse the data, normally the app that generated the file in the first place. Programming languages typically offer easy ways to store data in binary files. Java and other object-oriented languages can format objects as binary sequences for file storage. They also offer automated ways to recreate objects form the data.

4 Binary File I/O Output: FileOutputStream is a stream for output to a file. BufferedOutputStream is a stream with a buffer (write data in chunks for more efficiency, since there are fewer calls to the expensive input/output methods used by the operating system). BufferedOutputStream wraps an unbuffered stream such as a FileOutputStream to provide the buffer. DataOutputStream provides methods for writing objects to the stream it wraps. Methods like writeDouble() output the stated types All of these have equivalent input methods The following example stores low-level types like Double and uses parsing code when the file is read, but you will soon see an example that stores and retrieve collections of objects of programmer-defined classes.

5 package menudemo; // http://docs.oracle.com/javase/tutorial/essential/io/examples/DataStreams.java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataStreams { static final String dataFile = "invoicedata"; static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; static final int[] units = { 12, 8, 13, 29, 50 }; static final String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; public static void main(String[] args) throws IOException { DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile))); for (int i = 0; i < prices.length; i ++) { out.writeDouble(prices[i]); out.writeInt(units[i]); out.writeUTF(descs[i]); } } finally { out.close(); }

6 DataInputStream in = null; double total = 0.0; try { in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); double price; int unit; String desc; try { while (true) { price = in.readDouble(); unit = in.readInt(); desc = in.readUTF(); System.out.format("You ordered %d units of %s at $%.2f%n", unit, desc, price); total += unit * price; } } catch (EOFException e) { // this is really how Orace's documentation suggests you find the end of a file! System.out.println("EOF reached");} System.out.format("For a TOTAL of: $%.2f%n", total); } finally { in.close(); }

7 Binary I/O ObjectOutputStream and ObjectInputStream allow binary i/o of whole objects Objects read from files must be cast correctly Objects stored this way must be serializable, meaning they must implement the Serializable interface, which just identifies them as convertible to a binary stream. Serializable does not require any actual methods. If the object contains references to other objects, all the classes must be serializable!

8 Binary I/O Monster Tracker uses these classes: GUI class Monster MonsterHerd, which is a collection of Monsters MonsterPersister, which provides methods for binary i/o

9 Monster Tracker package monsterpersistence; import java.io.Serializable; public class Monster implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String name; private String hometown; private String rampageBehavior; public Monster(String nameIn, String hometownIn, String rampageBehaviorIn){ name = nameIn; hometown = hometownIn; rampageBehavior = rampageBehaviorIn; } public String getName() { return name; } public void setName(String name) { this.name = name; }

10 Monster Tracker public String getHometown() { return hometown; } public void setHometown(String hometown) { this.hometown = hometown; } public String getRampageBehavior() { return rampageBehavior; } public void setRampageBehavior(String rampageBehavior) { this.rampageBehavior = rampageBehavior; } public String toString (){ return name + " from " + hometown + " likes to " + rampageBehavior; }

11 Monster Tracker package monsterpersistence; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class MonsterHerd implements Serializable{ private static final long serialVersionUID = 1L; private List monsters = new ArrayList (); public List getMonsters() { return monsters; } public void addMonster(Monster m){monsters.add(m);} public String toString(){ StringBuilder sb = new StringBuilder(); for(Monster m: monsters) sb.append(m + "\n"); return sb.toString(); }

12 Monster Tracker package monsterpersistence; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class MonsterHerdPersister{ public void saveHerdToFile(File f, MonsterHerd mh) { ObjectOutputStream out = null; try { out = new ObjectOutputStream(new BufferedOutputStream( new FileOutputStream(f))); out.writeObject(mh); out.close(); } catch (Exception e) { e.printStackTrace(); } public MonsterHerd readHerdFromFile(File f) { ObjectInputStream in = null; MonsterHerd m = null; try { in = new ObjectInputStream(new BufferedInputStream( new FileInputStream(f))); m = (MonsterHerd) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } return m; }

13 Monster Tracker package monsterpersistence; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.util.List; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class MonsterGUI { MonsterHerd herd; JFrame frame = null; JPanel panel; JMenuBar menubar; JScrollPane scrollPane; JTable table;

14 Monster Tracker public MonsterGUI() { herd = new MonsterHerd(); initUI(); } public final void initUI() { frame = new JFrame(); panel = new JPanel(); table = setUpTable(); menubar = new JMenuBar(); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); final JFileChooser fc = new JFileChooser(); // enums like KeyEvent evaluate to ints createAndAddMenuItem(file, "Open", KeyEvent.VK_O, "Open File", new ActionListener() { public void actionPerformed(ActionEvent event) { int retVal = fc.showOpenDialog(frame); if (retVal == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); MonsterHerdPersister p = new MonsterHerdPersister(); herd = p.readHerdFromFile(selectedFile);

15 Monster Tracker updateTable(); } }); createAndAddMenuItem(file, "Add Monster", KeyEvent.VK_A, "Add Monster", new ActionListener() { public void actionPerformed(ActionEvent event) { String name = JOptionPane.showInputDialog(frame, "please enter the monster's name"); String hometown = JOptionPane.showInputDialog(frame, "please enter the monster's hometown"); String rampage = JOptionPane.showInputDialog(frame, "what does the monster do when it goes on a rampage?"); Monster m = new Monster(name, hometown, rampage); herd.addMonster(m); updateTable();

16 Monster Tracker } }); createAndAddMenuItem(file, "Save", KeyEvent.VK_S, "Save File", new ActionListener() { public void actionPerformed(ActionEvent event) { int retVal = fc.showOpenDialog(frame); if (retVal == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); MonsterHerdPersister p = new MonsterHerdPersister(); p.saveHerdToFile(selectedFile, herd); } }); createAndAddMenuItem(file, "Exit", KeyEvent.VK_E, "Exit application", new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); menubar.add(file); frame.setJMenuBar(menubar); frame.setTitle("Monsters");

17 Monster Tracker frame.setSize(600, 200); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); scrollPane = new JScrollPane(table); panel.add(scrollPane); frame.add(panel); frame.setVisible(true); } private void createAndAddMenuItem(JMenu menu, String message, int mnemonic, String tooltip, ActionListener a) { JMenuItem menuItem = new JMenuItem(message); menuItem.setMnemonic(mnemonic); menuItem.setToolTipText(tooltip); menuItem.addActionListener(a); menu.add(menuItem); }

18 Monster Tracker private JTable setUpTable(){ String[] columnNames = { "Name", "Hometown", "Rampage Behavior"}; Object[][] data = listToArray(herd.getMonsters()); JTable newTable = new JTable(data, columnNames); newTable.setPreferredScrollableViewportSize(new Dimension(500, 70)); newTable.setFillsViewportHeight(true); newTable.setAutoCreateRowSorter(true); newTable.doLayout(); return newTable; } private void updateTable() { for (Monster m : herd.getMonsters()) System.out.println(m); panel.removeAll(); table = setUpTable(); scrollPane = new JScrollPane(table); panel.add(scrollPane); panel.doLayout(); } private Object[][] listToArray(List list) { Object[][] array = new Object[list.size()][3]; for (int counter = 0; counter < list.size(); counter++) { array[counter][0] = list.get(counter).getName(); array[counter][1] = list.get(counter).getHometown(); array[counter][2] = list.get(counter).getRampageBehavior(); } return array; } public static void main(String[] args) { MonsterGUI ex = new MonsterGUI(); }

19 Recursion This topic is often covered in CS202-level classes, but the new textbook covers it just after the material for this course ends You may take CS203 with an instructor who expects you to understand recursion before you start the course. Recursion is also extremely important in CS312. Recursion is not hard to understand in principle, but students often have difficulty coding it correctly There is no time to cover it thoroughly here; this brief coverage is intended to give you a basic understanding of the principle. There may be multiple-choice questions on the last quiz or short- answer questions on the final about recursion, but you will not be required to write any recursive code in this course. Recursion will probably be the first major topic in CS203 next term.

20 Recursion Recursion is the technique of breaking down a problem into smaller instances of the same problem. A recursive method is a method that directly or indirectly calls itself – direct recursion: methodA calls methodA – indirect recursion: methodA calls methodB and methodB calls methodA Avoid infinite regression (and stack overflows) by defining a condition that causes termination of the recursion

21 King of Hearts’ Algorithm 21 "Where shall I begin, please your majesty?" he asked. "Begin at the beginning," the King said gravely, "and go on till you come to the end; then stop. "

22 Recursive Algorithm 22 doSomething() 1.If you are finished, stop. 2.Otherwise 1.Solve part of the problem 2.Run this algorithm

23 Recursion 23 For example, we can define the operation goHome() as: – If you are at home, stop. – Otherwise Take one step toward home. goHome()

24 Non-Recursive Factorial 24 function factorial is: input: integer n such that n >= 0 output: [n × (n-1) × (n-2) × … × 1] Iterative algorithm 1.create new variable called running_total with a value of 1 2.begin loop 1.if n is 0, exit loop 2.set running_total to (running_total × n) 3.decrement n 4.repeat loop 3.return running_total end

25 Recursive Factorial 25 You will see this algorithm again in future classes! function factorial: input: integer n such that n >= 0 output: [n × (n-1) × (n-2) × … × 1] 1.if n is 0, return 1 2.otherwise, return [ n × factorial(n-1) ]

26 Recursion 26 public class Demo { public static int factorialRecursive(int intIn){ if(intIn ==0) return 1; return intIn * factorialRecursive(intIn -1); } public static void main(String[] args) { int num = Integer.parseInt(JOptionPane.showInputDialog(null, "Please " + "enter the number whose factorial you would like to compute")); JOptionPane.showMessageDialog(null, "The factorial of " + num + " is " + factorialRecursive(num)); }

27 Another Recursive Example package demos; import java.util.ArrayList; import java.util.List; //https://stackoverflow.com/questions/126756/examples-of-recursive-functions public class RecursionExample { public static void main(String[] args) { String[] sleeplessArray = { "ant", "frog", "goose", "weasel", "child" }; List sleeplessList = new ArrayList (); for (String s : sleeplessArray) sleeplessList.add(s); RecursionExample r = new RecursionExample(); r.tellStory(sleeplessList); } public RecursionExample(){ System.out.print("There was a "); } private void tellStory(List sleeplessList) { int last=sleeplessList.size() -1; String animal = sleeplessList.get(last); if(sleeplessList.size() == 1) System.out.println("little " + animal +" who went to sleep"); else { System.out.println("little " + animal + " who couldn't sleep, \nso his mother told him a story about a "); sleeplessList.remove(last); tellStory(sleeplessList); System.out.println("and the little " + animal + " went to sleep" ); }

28 Recursion 28 Function recurse() 1.If you are done with your program, stop 2.Otherwise, A. Try to find the problem B. Utter an obscenity 3.recurse()


Download ppt "Lecture 14 CS202. JUnit on the Final The programming questions on the Sample and actual final exams will require you to write Junit tests. Be sure to."

Similar presentations


Ads by Google