Midterm 2 Review 1. 2 Object Oriented Programming Write a Date class. It should contain fields for day, month, year, number of months per year, and number.

Slides:



Advertisements
Similar presentations
Graohics CSC 171 FALL 2001 LECTURE 16. History: COBOL Conference on Data System Languages (CODASYL) - led by Joe Wegstein of NBS developed the.
Advertisements

More Java Syntax. Scanner class Revisited The Scanner class is a class in java.util, which allows the user to read values of various types. There are.
Final Review.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Files and Streams CS 21a Chapter 11 of Horstmann.
Client/Server example. Server import java.io.*; import java.net.*; import java.util.*; public class PrimeServer { private ServerSocket sSoc; public static.
18 File handling1June File handling CE : Fundamental Programming Techniques.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Building Java Programs
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Tallying and Traversing Arrays reading: 7.1 self-checks: #1-9 videos:
Introduction to Java Programming Language May 2015 Kyung Eun Park COSC Introduction to Computer Science II.
Multi-Dimensional Arrays Rectangular & Jagged Plus: More 1D traversal.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Tallying and Traversing Arrays reading: 7.1 self-checks: #1-9 videos:
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 4.3, 7.6.
03/16/ What is an Array?... An array is an object that stores list of items. Each slot of an array holds an individual element. Characteristics.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
Type Safety and Enumerations. Type Checking and Type Errors  The type system defines data types and the operations on data types.  A type error occurs.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CS 2430 Day 9. Announcements Quiz on Friday, 9/28 Prog1: see , see me as soon as possible with questions/concerns Prog2: do not add any public methods.
F27SA1 Software Development 1 9. Java Programming 8 Greg Michaelson.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.6, 4.3.
F27SA1 Software Development 1 7. Java Programming 6 Greg Michaelson.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
Writing Static Methods Up until now, we have been USING (calling) static methods that other people have written. Now, we will start CREATING our own static.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Objects & Classes Weiss ch. 3. So far: –Point (see java.awt.Point) –String –Arrays of various kinds –IPAddress (see java.net.InetAddress) The Java API.
Arrays and Objects CIS 362. The familiar Employee class.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.1, 4.4 self-checks: #1-9.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Jeopardy Print Me Which loop? Call Me Name Me My Mistake Q $100 Q $200 Q $300 Q $400 Q $500 Q $100 Q $200 Q $300 Q $400 Q $500 Final Jeopardy.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 17: Arrays for Tallying; Text Processing reading: 4.3, 7.6 (Slides adapted.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
WAP to find out the number is prime or not Import java.util.*; Class Prime { public static void main(string args[]) { int n,I,res; boolean flag=true;
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Chapter 9 Introduction to Arrays Fundamentals of Java.
I/O in java and Revision. 2 I/O in Java Many packages and libraries associated with Java provide sophisticated ways to input and output information, e.g.:
Object Oriented Programming Lecture 2: BallWorld.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Java: Base Types All information has a type or class designation
COMPUTER 2430 Object Oriented Programming and Data Structures I
CS 160 Final Review.
Reading from a file and Writing to a file
Java: Base Types All information has a type or class designation
Yanal Alahmad Java Workshop Yanal Alahmad
Strings and File I/O.
Computer Programming Methodology Input and While Loop
CS Week 14 Jim Williams, PhD.
Building Java Programs
Building Java Programs
An Introduction to Java – Part I, language basics
Building Java Programs
Lecture 7-3: Arrays for Tallying; Text Processing
Building Java Programs
Building Java Programs
Chapter 6 Array-Based Lists.
Arrays and Array Lists CS 21a.
slides created by Ethan Apter
Building Java Programs
CSC1401 Input and Output (with Files)
Building Java Programs
Building Java Programs
More on iterations using
Presentation transcript:

Midterm 2 Review 1

2 Object Oriented Programming Write a Date class. It should contain fields for day, month, year, number of months per year, and number of days per month. Write a constructor to initialize the instance fields Write a compareTo(Date other) method that determines which of two Date objects is later in time. compareTo should return 1 if the “other” Date is later, -1 if the “this” Date is later, and 0 if they are the same date.

Solution public class Date { public int day; public int month; public int year; public static final int numMonthsPerYear = 12; public static final int [] numDaysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; }

Solution, continued public int compareTo(Date other) { if(other.year>this.year) { return 1; } else if(other.year<this.year) { return -1; } else if(other.month > this.month) { return 1; } else if(other.month < this.month) { return -1; } else if(other.day > this.day) { return 1; } else if(other.day < this.day) { return -1; } else { return 0; }

OOP, continued Write a Calendar class that holds a separate Date object for every day in November. In the main method, have it print out every date in a sequence, 7 dates per line. If we modify the fields in the Date to be private, how can we change Date and Calendar so that the main method can still print out the dates?

Solution 1 public class Calendar { public Date [] november2009; public Calendar() { november2009 = new Date[Date.numDaysPerMonth[10]]; for(int i=0; i<november2009.length; i++) { november2009[i] = new Date(i+1,11,2009); } private static void printDate(Date d) { System.out.print(d.month + "/" + d.day + "/" + d.year); } public static void main(String [] args) { for(int i=0; i<november2009.length; i++) { printDate(november2009[i]); if(i%7==6) { System.out.println(); }

Solution 2 Change Date instance fields to private Add a toString() method to Date: public String toString() { return this.month + “/” + this.day + “/” + this.year; } Get rid of printDate(), and change main() in Calendar to use toString: public static void main(String [] args) { for(int i=0; i<november2009.length; i++) { System.out.print(november2009[i].toString()); if(i%7==6) { System.out.println(); }

Array Programming Write a method that takes two ints as arguments: size and value. It should return an array with the given size, whose elements all have the given value. Write a method that returns the average value of a two- dimensional double array. Write a method that takes an int Num as an argument, and returns an array containing the first Num numbers in the Fibonacci sequence. Do the same with an ArrayList instead

Solutions public static int [] createConstantArray( int size, int value) { int [] result = new int[size]; for(int i=0; i<result.length; i++) { result[i] = value; } return result; }

Solutions, continued public static double average2D(double [][] array) { double sum = 0; int count = 0; for(int i=0; i<array.length; i++) { for(int j=0; j<array[i].length; j++) { sum += array[i][j]; count++; } return sum / count; }

Solutions, continued public static int [] fibonacciSequence(int n) { if(n<=0) { return null; } int [] result = new int[n]; if(n>=1) { result[0] = 1; } if(n>=2) { result[1] = 1; } for(int i=2; i<result.length; i++) { result[i] = result[i-1] + result[i-2]; } return result; }

Solutions, continued public static ArrayList fibonacciSequence(int n) { ArrayList result = new ArrayList (); if(n>=1) { result.add(1); } if(n>=2) { result.add(1); } for(int i=2; i<n; i++) { int prev = result.get(result.size()-1); int prev2 = result.get(result.size()-2); result.add(prev+prev2); } return result; }

File Programming Create a “FileEncrypter” class that reads in every word of a file (containing all lower case alphabetic words), and shifts the letters by some number x. For instance, if x=2, then FileEncrypter would change “zebra” to “bgdtc” (shifting every letter by 2). Store the encrypted file into a new file. Write a “FileDecrypter” class that reads in an encrypted file, and decrypts it. The FileDecrypter needs to know the number x that the File Encrypter used, to reverse the process.

Solution: FileEncrypter import java.util.*; import java.io.*; public class FileEncrypter { public static void main(String [] args) throws FileNotFoundException { if(args.length<3) { System.out.println( “Usage: java FileEncrypter ”); } int key = Integer.parseInt(args[2]); encrypt(args[0], args[1], key); }

Solution: FileEncrypter, continued public static void encrypt(String infile, String outfile, int key) throws FileNotFoundException { Scanner in = new Scanner(new File(infile)); PrintWriter pw = new PrintWriter(new File(outfile)); while(in.hasNext()) { String word = in.next(); String jumble = encryptWord(word, key); pw.println(jumble); } in.close(); pw.close(); }

Solution: FileEncrypter, continued public static String encryptWord(String word, int key) { String result = “”; for(int i=0; i<word.length(); i++) { result += encryptLetter(word.charAt(i), key); } return result; } public static char encryptLetter(char letter, int key) { int num = letter + key; while(num > ‘z’) { num -= 26; } while(num < ‘a’) { num += 26; } return (char) num; }

Solution: FileDecrypter import java.util.*; import java.io.*; public class FileDecrypter { public static void main(String [] args) throws FileNotFoundException { if(args.length<3) { System.out.println( “Usage: java FileDecrypter ”); } int key = Integer.parseInt(args[2]); decrypt(args[0], args[1], key); }

Solution: FileDecrypter, continued public static void decrypt(String infile, String outfile, int key) throws FileNotFoundException { Scanner in = new Scanner(new File(infile)); PrintWriter pw = new PrintWriter(new File(outfile)); while(in.hasNext()) { String word = in.next(); String jumble = decryptWord(word, key); pw.println(jumble); } in.close(); pw.close(); }

Solution: FileDecrypter, continued public static String decryptWord(String word, int key) { String result = “”; for(int i=0; i<word.length(); i++) { result += decryptLetter(word.charAt(i), key); } return result; } public static char decryptLetter(char letter, int key) { // add key to encrypt, subtract to decrypt int num = letter - key; while(num > ‘z’) { num -= 26; } while(num < ‘a’) { num += 26; } return (char) num; }