New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Problem Solving And Object

by: Nick Rowe

Problem Solving And Object CS 18000

Marketplace > Purdue University > ComputerScienence > CS 18000 > Problem Solving And Object
Nick Rowe
GPA 3.68

Sunil Prabhakar

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Sunil Prabhakar
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 75 page Class Notes was uploaded by Nick Rowe on Saturday September 19, 2015. The Class Notes belongs to CS 18000 at Purdue University taught by Sunil Prabhakar in Fall. Since its upload, it has received 21 views. For similar materials see /class/208063/cs-18000-purdue-university in ComputerScienence at Purdue University.


Reviews for Problem Solving And Object


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/19/15
Chapter 12 File Input and Output CS 180 Sunil Prabhakar Department of Computer Science Purdue University Persistent Data I Suppose we write a Bank application I How do we remember the account balances What if the bank application stops running 0 Runtime exception 0 Power failure 0 How do we ensure that when we restart the application the balances are set correctly PURDUE File O Remember that a computer system has two types of memory 0 Fast volatile main memory 0 Slower nonvolatile secondary memory disk When a program runs its variables primitive and objects are stored in main memory When the program terminates all these variables are lost If we would like to preserve values of variables across multiple executions we must save them on disk and read them back in file input and output File lO PURDUE File lO I Files can also be used to prevent loss of data due to system failures Files can serve as a means for sharing data between different programs Different operating systems manage files differently Since Java is a HLL we are mostly shielded from these differences In Java we use objects to perform file O PURDUE 4 Chapter 12 Objectives I This week we will study 0 Choosing files using JFiIeChooser 0 Reading from and writing to files Bytes using FileOutputStream and FilelnputStream Primitive data types using DataOutputStream and DatalnputStream Text data using PrintWriter and BufferedReader Objects using ObjectOutputStream and ObjectlnputStream 0 Reading a text file using Scanner PURDUE The File Class I To operate on a file we must first create a File object from javaio Fi1e inFi1e new Fi1e samp1edat I Fi1e inFi1e new Fi1e C2Samp1eProgramstestdatquot PURDUE File names I The rules for file names are determined by the operating system on which the Java program is run Thus the name may or may not be case sensitive or require filename extensions Java simply passes the string to the operating system PURDUE Some File Methods if139nF1391e139sF1391e Fi1e directory new Fi1equotCJavaProgramsCh12quot String fi1ename directory1ist for int i 0 i lt fi1ename1ength i Systemoutprint1nfi1enamei PURDUE The JFileChooser Class I A javaxswingJFileChooser object allows the user to select a file JFileChooser chooser new JFileChooser choosershowOpenDialognu11 To start the listing from a specific directory JFileChooser chooser new JFileChooserquotDJavaProgramsCh12quot choosershowOpenDialognull P URDUE Getting Info from JFiIeChooser int status choosershowOpenDia1ognu11 if status JFi1eChooserAPPROVEOPTION JOptionPaneshowMessageDia1ognu11 quotOpen is c1ickedquot e1se JFiTeChooserCANCELOPTION JOptionPaneshowMessageDia1ognu11 quotCance1 is c11ckedquot Fi1e se1ectedFi1e choosergetSe1ectedFi1e Fi1e currentDirectory choosergetCurrentDirectory P URDUE Applying a File Filter I A le lter may be used to restrict the listing in JFiIeChooser to only those filesdirectories that meet the designated filtering criteria I To apply a filter we define a subclass of the javaxswingfilechooserFileFilter class and provide the accept and getDescription methods pub39l ic boo39l ean accept F1 1e f1 1 e pub139ic String getDesc r139 pt139 on I See the JavaFilter class that restricts the listing to directories and Java source files PURDUE 122 LOWLevel File lO I To read data from or write data to a file we must create one of the Java stream objects and attach it to the file A stream is a sequence of data items usually 8 bit bytes Java has two types of streams an input stream and an output stream An input stream has a source form which the data items come and an output stream has a destination to which the data items are going PURDUE Streams for LowLevel File lO I FileOutputStream and FilelnputStream are two stream objects that facilitate file access FileOutputStream allows us to output a sequence of bytes values of data type byte FilelnputStream allows us to read in an array of bytes PURDUE Sampe LowLevel File Output set up Fi1e and stream Fi1e outFi1e new Fi1equotsamp1eldataquot Fi1e0utputStream outStream new Fi1e0utputStream outFi1e data to save byte byteArray 10 20 30 40 50 60 70 80 wr1te data to the Stream outStreamwrite byteArray 0utput done so c1059 the Stream outStreamc1ose PURDUE Sample LowLevel File Input set up F11e and stream Fi1e inFi1e new Fi1equotsamp1eldataquot Fi1eInputStream inStream new Fi1eInputStreaminFi1e set up an array to read data in int fi1eSize intinFi1e1ength byte byteArray new bytefi1eSize read data in and disp1ay them inStreamreadbyteArray For int i 0 i lt fi1eSize i Systemoutprint1nbyteArrayi 1nput done so c1ose the stream inStreamc1ose PURDUE Opening and closing files I When we create the stream object we open the file and connect it to the stream for input or output Once we are done we must close the stream Othenvise we may see corrupt data in the file If a program does not close a file and terminates normally the system closes the files for it We must close a file after writing before we can read from it in the same program PURDUE Streams for HighLevel File lO I FileOutputStream and DataOutputStream are used to output primitive data values I FilelnputStream and DatalnputStream are used to input primitive data values I To read the data back correctly we must know the order of the data stored and their data types PURDUE Setting up DataOutputStream F1391e outF1391e new F1391e quotsamp1e2dataquot F1391e0utputStr eam outF1391eStr eam new F139 1 eOutputStr eamoutF139 1 e DataOutputStream outDataStr eam new DataOutputSteamoutF11eStr eam writeFloat writeInt writeDouble outData Stream outFile Stream sampleZ dat outFile PURDUE Sample Output import javaio ciass ChlZTestDataOutputStream pub1ic static void main String args throws IOException set up outDataStream write vaiues of primitive data types to the stream outDataStreamwriteInt987654321 outDataStreamwriteLongllllllllL outDataStreamwriteF10at22222222F outDataStreamwriteDoub1e3333333D outDataStreamwriteChar39A39 outDataStreamwriteBooieantrue output done so ciose the stream outDataStreamciose PURDUE Setting up DatalnputStream F1391e inF1391e new F1391e quotsamp1e2cataquot F1391eInputStr eam 139 nF1391eStr eam new F1391eInputStr eam139nF1391e DataInputStr eam 139 nDataStr eam new DataInputSteam139nF1391eStr eam readFloat readInt readDouble inDataStream inFile Stream sampleZ dat PURDUE Sample Input 1mport javaio c1ass ChlZTestDataInputStream pub1ic static void main String args throws IOException set up 1nDataStream read System System System System System System va1ues back from the stream and disp1ay them out out out out out out print1ninDataStream print1ninDataStream print1ninDataStream print1ninDataStream print1ninDataStream print1ninDataStream readInt readLong readF1oat readDoub1e readChar readBoo1ean input done so c1ose the stream inDataStreamc1ose PURDUE Reading Data Back in Right Ord r I The order of write and read operations must match in order to read the stored primitive data back correctly outStr eamwr 1teLong outStr eamwr 1teChar outStr eamwr 1 teBooi ean outSt r eam wr j teI ntege r ltintegergt donggt ltchargt ltbodeangt jnStr eam r eadLong 1nStr eam readChar 1 nStr eam r eadBooi ean inStr eam r eadIntecEJer PURDUE Types of files I There are two main types of files 0 Text store characters ASCII or UNICODE I java I Usually platform independent but less efficient O Binary may store any type of data I class exe I Often depend on machine OS program I Java binary files are platform independent I Text files are editable using editors and usually comprehensible to humans I So far we have been dealing with binary files in this discussion PURDUE Textfile Input and Output I Instead of storing primitive data values as binary data in a file we can convert and store them as string data 0 This allows us to view the file content using any text editor To output data as a string to file we use a PrintWriter object To input data from a textfile we use FileReader and BufferedReader classes 0 From Java 50 SDK 15 we can also use the Scanner class for inputting textfiles PURDUE Sample Textfile Output import javaio c1ass ChlZTestPrintWriter pub1ic static void main String args throws IOException set up fi1e and stream Fi1e outFi1e new Fi1equotsamp1e3dataquot Fi1e0utputStream outFi1eStream new Fi1e0utputStreamoutFi1e PrintWriter outStream new PrintWriteroutFi1eStream write va1ues of primitive data types to the stream outStreamprint1n987654321 outStreamprint1nquotHe110 wor1dquot outStreamprint1ntrue output done so c1ose the stream outStreamc1ose PURDUE PrintWriter I If a file with the given name exists it is opened for output and its current contents are lost I If we want to retain the old data and append to the end of the file FiieOutputStream outFiieStream new F1391e0utputStreamCoutFiie true then create the PrintWriter object with this stream object PURDUE Sample Textfile Input import javaio c1ass ChlZTestBufferedReader pub11c static void main String args throws IOException set up f11e and stream Fi1e inFi1e new Fi1equotsamp1e3dataquot Fi1eReader fi1eReader new Fi1eReaderinFi1e BufferedReader bufReader new BufferedReaderfi1eReader String str str bufReaderreadLine IntegerparseIntstr int i simi1ar process for other data types bufReaderc1ose PURDUE Notes I FileReader is meant to be used for reading in character streams I FilelnputStream is for arbitrary streams I BufferedReader is much more efficient that reading directly from an input stream 0 automatically buffers input from the stream 0 can be much more efficient due to disk lO costs PURDUE Sample Textfile Input with Scanner import javaio import javauti1 c1ass ChlZTestScanner pub1ic static void main String args throws IOException open the Scanner Scanner scanner new Scannernew Fi1equotsamp1e3dataquot get integer int i scannernextInt simi1ar process for other data types scannerc1ose PURDUE Object File lO It is possible to store objects just as easily as you store primitive data values We use ObjectOutputStream and ObjectlnputStream to save to and load objects from a file To save objects from a given class the class declaration must include the phrase implements Serial izabl e For example c39lass Person imp1ements Serializable PURDUE Saving Objects Fi1e outFi1e new F11equotobectsdataquot Fi1e0utputStream outFi1eStream new F11e0utputStreamoutF11e ObjectOutputStream outObjectStream ObjectOutputStreamoutF3Egkream Person person new PersonquotMr Espressoquot 20 outObjectStreamwriteObject person accountl bankl new Account new Bank outObjectStreamwr1teObjectE accountl 3 outObjectStreamwr1teObject bankl 39 PURDUE Reading Objects Fi1e inFi1e I new F11equotobectsdataquot Fi1eInputStream inFi1eStreqm new F11eInputStream1nF11e ObjectInputStream inObjectStream n ew ObjectInputStreaminFi1eStream Person person Person inObjectStreamreadObjectC Account accountl ccount 1n0bjectStreamreadObect Bank bankl Bank 1n0bjectStreamreadObect PURDUE Saving and Loading Arrays I Instead of processing array elements individually it is possible to save and load the entire array at once Person people new Person N assume N already has a value build the people array save the array outObjectStreamwriteObject people read the array Person people Person inObjectStreamreadObject PURDUE Exceptions I File lO methods throw various types of exceptions including 0 lOException o FileNotFoundException Please see Java API to become familiar with these Many of these need to be handled in order to make programs more robust Labs and projects will cover some PURDUE Knowing when to stop reading I It is possible to try to read beyond the end of the file Different reader classes signal the end of file in different ways Binary file readers throw the EOFException Text file readers return null or 1 You should be aware of how the common classes indicate the end of file condition PURDUE 35 Introducing Theory of Computation I What are the limits of computers I What can a computer not compute 0 Today 0 In 10 years 0 Ever I These are some of the questions that the theory of computation tries to answer I Covered in C8483 C8182 C8380 PURDUE A model for any computer I In order to answer such questions we first begin with a model for a computer I Actually we begin by considering very simple machines called automata I These are really primitive beasts and come in several species 0 1way finite automata o 2way finite automata o Turing Machine PURDUE The Turing Machine Named after Alan Turing Consists of 0 Input tape with symbols 0 A control consisting of a graph 0 Machine can I read the current symbol write to the current place move the tape left or right and change its state I Looks primitive but is capable of computing anything that any modern computer can PURDUE What are the limits of this machine I Can it compute the factorization of a prime number Sure but how long will it take 0 500 digits life of universe with a supercomputer 0 Security cryptography relies on this How long is too long 0 Polynomial time Can it compute the factorization using a better algorithm in polynomial time Can we prove that there can be no fast algorithm for certain problems PURDUE Guessing computers Consider a Turing Machine which can take one of many options at each step If any guess gives us the correct answer then we have solved the problem Many problems like factoring can be solved by such a machine in polynomial time But such machines do not exist PURDUE NPCompleteness I Problems that can be solved in polynomial time by a guessing machine but not by a Turing Machine are called NPComplete If any of these is solved efficiently then all of them will be solved efficiently I Is this possible le is P NP I We don t know if you have the answer you can 0 Get the ACM Turing Award CS Nobel Prize 0 Get a great job PURDUE 41 08438 08380 CS182 I These courses study the issues of computability I What are the limits of computers I When should we stop trying to find a fast algorithm Ifthere is no known fast algorithm what can we do 0 Heuristics What happens if we get new types of computers PURDUE 42 Problem Statement Write a class that manages le 0 of an AddressBook object PURDUE Development Steps I We will develop this program in four steps Implement the constructor and the setFile method Implement the write method Implement the read method Finalize the class PURDUE Step 1 Design I We identify the data members and define a constructor to initialize them I Instead of storing individual Person objects we will deal with a AddressBook object directly using Object lO techniques PURDUE Step 1 Code ngmmsmmmmeSmOMth haemenmNmee k you to View the source files using your Java IDE Directory Chapter12Step1 Source Files AddressBookStoragejava TestAddressBookStoragejava PURDUE Step 1 Test I We include a temporary output statement inside the setFile method I We run the test main class and verify that the setFile method is called correctly PURDUE Step 2 Design Design and implement the write method The data member filename stores the name of the object file to store the address book We create an ObjectOutputStream object from the data member filename in the write method The write method will propagate an IOException when one is thrown PURDUE Step 2 Code Directory Chapter12Step2 Source Files AddressBookStoragejava TestAddressBookWritejava PURDUE Step 2 Test We run the test program several times with different sizes for the address book We verify that the resulting files indeed have different sizes At this point we cannot check whether the data are saved correctly or not 0 We can do so only after finishing the code to read the data back PURDUE Step 3 Design Design and implement the read method The method returns an AddressBook object read from a file if there39s no excep on The method will propagate an IOException when one is thrown PURDUE Step 3 Code Directory Chapter12Step3 Source Files AddressBookStoragejava TestAddressBookReadjava PURDUE Step 3 Test I We will write a test program to verify that the data can be read back correctly from a file I To test the read operation the file to read the data from must already exist I We will make this test program save the data first by using the TestAddressBookWrite class from PURDUE Step 4 Finalize I We perform the critical review of the final program I We run the final test PURDUE Chapter 6 Repetition Statements CS 180 Prof Sunil Prabhakar Department of Computer Science Purdue University Objectives After this week you should be able to PURDUE Understand looping constructs 0 while dowhile for Understand nested looping statements Implement a generic loopandahalf repetition control statement Prompt the user for a yesno reply using the showConfirmDialog method of JOptionPane Definition Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met Countcontrolled repetitions terminate the execution of the block after it is executed for a fixed number of times Sentinelcontrolled repetitions terminate the execution of the block after one of the designated conditions called a sentinel is encountered Repetition statements are also called loop statements PURDUE The while Statement int sum 0 number l whi1e number lt 100 m c 3 sum number 1 number l PUBDUE Syntax for the while Statement wh i1e ltboo1ean expressiongt ltstatementgt wh1quote number lt 10039 Sllll gili iIIljFrBEF quotu 39number number l PURDUE Control Flow of while previous statement int sum 0 number 1 sum sum number number number number 1 false next statement PURDUE More Examples ltgt int sum 0 number l whi1e sum lt 1000000 sum sum number number number l int product 1 number 1 count 20 1astNumber 1astNumber 2 count l whi1e number lt 1astNumber product product number number number 2 PURDUE Finding GCD pub1ic int gcdbruteforceint m int n pub1ic int gcd int m int n assume mquot gt 1 it doesn t matter which of n int 1aSt Mathm1nmn and m is bigger this method int gcd wi11 work fine either way int i l whi1e i lt 1ast assume mn gt 1 if m 1 0 ampamp n 1 0 int r n m gcd i whi1e r 0 n m 1 return gcd return m Direct Approach More Efficient Approach Euclid PURDUE Example Testing Input Data String inputStr int age inputStr JOptionPaneshowInputDia1ognu11 quotYour Age between 0 and 130quot age IntegerparseInt inputStr wh11e age lt 0 ll age gt 130 JOptionPaneshowMessageDia1og nu11 quotAn inva1id age was entered P1ease try againquot inputStr JOptionPaneshowInputDia1og nu11 quotYour Age between 0 and 130quot age IntegerparseInt inputStr PURDUE Useful Shorthand Operators sum sum number a sum number Operator Meaning aab aab aab aab aab PURDUE Watch Out for Pitfalls Watch out for the offbyone error OBOE Make sure the loop body contains a statement that will eventually cause the loop to terminate Make sure the loop repeats exactly the correct number of times If you want to execute the loop body N times then initialize the counter to O and use the test condition counter lt N or initialize the counter to 1 and use the test condition counter lt N PURDUE Loop Pitfall 1 ltgt int product 0 wh11e product lt 500000 product product 5 int count l whi1e count 10 count count 2 PURDUE Overflow An infinite loop often results in an overflow error An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold In Java an overflow does not cause program termination With types float and double a value that represents infinity is assigned to the variable With type int the value wraps around and becomes a negative value PURDUE Loop Pitfall 2 CD F1oat count 00f whi1e count 10f count count 03333333f seven 35 F1oat count 00f whi1e count 10f count count 033333333f eight 35 PUBDUE Loop Pitfall 2a 6 int resu1t 0 doub1e cnt 10 wh11e cnt lt 100 cnt 10 resu1t Systemoutprint1n resu1t int resu1t 0 doub1e cnt 00 wh11e cnt lt l0 cnt 01 resu1t Systemoutprint1n resu1t gt11 PURDUE Loop Pitfall 3 I Goal Execute the loop body 10 times count 1 count l wh11e count lt 10 whi1e count lt 10 count count count 0 count 0 wh39i39le count lt 10 whi39le count lt 10 count count CD and exhibit offbyone error PURDUE The do while Statement int sum 0 number l 39 sum number E number whi1e C sum lt 1000000 PURDUE Syntax for the do while Statement PURDUE do ltstatementgt whi1e C ltboo1ean expressiongt do sum number 3 1number j Wh e C 3 Hmui99999 lu3 Control Flow of while previous statement int sum 0 number1 sum number number number lt 100 next statement PURDUE The for Statement int i sum 0 number for i O i lt 20 i number scannerneXtInt i sum number PURDUE


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.