Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 6: September 26-30, 2011 Aditya Mathur Department of Computer Science Purdue.

Similar presentations


Presentation on theme: "CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 6: September 26-30, 2011 Aditya Mathur Department of Computer Science Purdue."— Presentation transcript:

1 CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 6: September 26-30, 2011 Aditya Mathur Department of Computer Science Purdue University West Lafayette, IN, USA http://www.cs.purdue.edu/homes/apm/courses/CS180Fall2011/ 1.Data input from files 2.Data output to file 3.Demo 4.Quiz 5.More on loops 6.Demo 9/26- 9/27 This Week:

2 Readings and Exercises for Week 6 Readings: Chapter 5: 5.1, 5.2, 5.3, 19.1, 19.2, 19.3 Exercises: Work on individual steps in Project 2. 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 62

3 Special help session Sunday October 2: 4-7pm LWSN 3142A/B 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 63

4 Announcements 1.Project 2 now available. Due date: Friday October 14, 2011 Recommended: Friday October 7, 2011 1.Project 1 not submitted? Can still submit it if you wish to be graded. 1.Problems with turnin? Contact your recitation Recitation TA, not the lab TA 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 64

5 9/26/2011 Data Input and Output using files ©Aditya Mathur. CS 180. Fall 2011. Week 65

6 9/26/2011 What is a file? Why files? A file is a collection of data items that generally, though not always, resides on a disk. Some programs are required to read data to a file. Some programs are required to write data into a file. Sometimes files containing data are created by human beings, while at other times a program might create a data file. Files make it easier to record and reuse data as compared to the user having to type the data each time a program executes. Recall how you tested Project 1? Was it not a pain? ©Aditya Mathur. CS 180. Fall 2011. Week 66

7 9/26/2011 Create a file for data input File cancerFile=new File(“cancerDataFile.txt”); Creates a virtual File object named cancerFile with path name cancerDataFile.txt Scanner cancerData=new Scanner(cancerDataFile); Creates a Scanner object named cancerData that will allow reading from cancerDataFile. Now we can use the well known methods to read from cancerDataFile using the cancerData object. ©Aditya Mathur. CS 180. Fall 2011. Week 67

8 9/26/2011 Reading from a file: Methods Scanner cancerData=new Scanner(cancerDataFile); ©Aditya Mathur. CS 180. Fall 2011. Week 68 String aLine= cancerData.nextLine(); // Read a line of characters (a string) int year= cancerData.nextInt();// Read an int String token= cancerData.next(); // Read the next token ( a string)

9 9/26/2011 Reading from a file: Does the file have any unread data? Scanner cancerData=new Scanner(cancerDataFile); ©Aditya Mathur. CS 180. Fall 2011. Week 69 cancerData.hasNext() Returns true if the file has any characters to be read, else it returns false. Useful in creating loops. while(cancerData.hasNext()){ }

10 9/26/2011 Writing to a file File dataOut=new File(“cancerData.txt”); Creates a virtual File object named dataOut with path name cancerData.txt. PrintWriter cancerData=new PrintWriter(dataOut); Creates a PrintWriter object named cancerData that will allow writing to cancerData.txt. Now we can use the well known methods (e.g. println() ) to write data to cancerData.txt using the cancerData object. ©Aditya Mathur. CS 180. Fall 2011. Week 610

11 9/26/2011 Writing to a file: Methods PrintWriter cancerData=new PrintWriter(dataOut); ©Aditya Mathur. CS 180. Fall 2011. Week 611 cancerData.println(“Hello”);// Write a string to a file cancerData.print(number);// Write an int to a file

12 Example 1: Word count 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 Write a program that reads an input text and computes and displays the count of the number of occurrences of a given word w. Assume that the text is is to be input from a file named puppy.txt. Define w in the program. 12

13 Word count: Understand how to solve the problem 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 w=“CS180” text=“One night I was studying for CS180.” 13 Start search here at startIndex=0 First occurrence at wordIndex=29 Continue at startIndex 34

14 Word count: Algorithm: 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 5 1.Define w. 2.Read text; 3.Initialize count to 0. 4.Initialize startIndex to 0. 5.while(startIndex<length of text){ Search for w from startIndex; If w found then { increment count ; Update startIndex; }else{ startIndex=length of text; } }// End of loop 6. Display count. 14 Loop to count occurrences of w in text Why this?

15 Announcements: Examination 1 1.Monday October 3. 8-10pm. Phy 112 and Phy 114 2.One question from Chapter 1 (no IEEE format but fractions will be covered). 3.Two programming questions; one problem requires if-else statement; second problem requires while. 4.Seating arrangement: PHY 112: All those with first names starting with A through L. PHY 114: All those with first names starting with M through Z. 5. Please bring your student ID to the exam. 6. And bring one Java book to consult during the exam. 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 615

16 Announcements: Others Feast with Faculty: September 28, 6:30pm Ford Dining Hall Dining room on the second floor (to your right when you arrive on the second floor ) 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 616

17 Quiz: 9/28/2011 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 617

18 Q1. int sum=0; Random r=new Random (); int num=r.nextInt(10); while (sum<100 || num!=0){ sum=sum+num; } The loop will terminate when (a)num is 0 (b)sum is equal to or greater than 100 and num is 0 (c)Sum is less than 10 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 618 Correct answer: b

19 Q2. int sum=0, num=0; while (num<3){ num=num+1; sum=sum+num; } The value of sum upon loop termination is 9/26/2011 (a)3 (b)6 (c)2 (d)1 ©Aditya Mathur. CS 180. Fall 2011. Week 619 Correct answer: b

20 Q3. int sum=0, num=0; while (num<3){ sum=sum+num; num=num+1; } The value of sum upon loop termination is 9/26/2011 (a)3 (b)6 (c)2 (d)1 ©Aditya Mathur. CS 180. Fall 2011. Week 620 Correct answer: a

21 Q4. int sum=0, num=1; while (num<4){ if(num%2==0){ sum=sum+num; } num=num+1; } The value of sum upon loop termination is (a)3 (b)6 (c)2 (d)1 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 621 Correct answer: c

22 End of Quiz: 9/28/2011 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 622

23 Live demo, word count problem [continued from Monday September 26, 2011] 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 523

24 9/26/2011 Example 2: Problem Statement A data file named “puppy.txt” contains lines of text. We are required to read each line from the file and process it as follows. Ignore all text that appears prior to, and including the string “CS180”, and print on the console all text that appears immediately following the string “CS180”. Any text that appears after the second occurrence of the string “CS180” should also be ignored, including the string “CS180”. ©Aditya Mathur. CS 180. Fall 2011. Week 624

25 9/26/2011 Example 2: Sample input file puppy.txt One night I was studying for CS180. It was real dark outside. And I heard a puppy crying. I thought to myself: “Halloween is several weeks away, what is this puppy-crying noise?” The noise persisted. I dragged myself out of the bed and followed the noise. The noise took me to a bathroom. There I saw a little puppy sitting under the tap with water drops falling on him! I took the puppy in my arms and brought it to my room. It was cold so I gave warm milk. He slurped it up and then slept quietly in a corner. I resumed studying for CS180. That was some experience! This was 40 years ago. The puppy lived with me for 15 years! ©Aditya Mathur. CS 180. Fall 2011. Week 625 Output: All text in green.

26 Live demo 9/21/2011©Aditya Mathur. CS 180. Fall 2011. Week 526

27 9/26/2011 Example 3: Problem Statement A drug manufacturing company has developed a new drug for treating a certain type of cancer. The company has performed experiments to determine the effectiveness of this drug in preventing cancer cells from multiplying. Effectiveness data obtained from the experiments is available in a file named cancerData. We need to write a program to obtain the average, minimum and maximum effectiveness of the drug. ©Aditya Mathur. CS 180. Fall 2011. Week 627

28 9/26/2011 Problem: Data format Data obtained from the experiments is available in a file named cancerData in the following format Code name of the drug: a string of characters For each experiment: Percent of cells prevented from multiplying ©Aditya Mathur. CS 180. Fall 2011. Week 628

29 9/26/2011 Algorithm: Initialization Open file cancerData; Get name of the drug; maxEff=0; // Maximum effectiveness minEff=101; // Minimum effectiveness effTotal=0; // Sum of all effectiveness data numExp=0; // Number of data items processed so far ©Aditya Mathur. CS 180. Fall 2011. Week 629

30 9/26/2011 Algorithm: Loop while(data remains to be processed){ eff=get effectiveness from the next experiment; numExp=numExp+1; effTotal=effTotal+eff; if(maxEff<eff) maxEff=eff; if(minEff>eff) minEff=eff; } ©Aditya Mathur. CS 180. Fall 2011. Week 630

31 9/26/2011 Algorithm: Post processing Average eff=effTotal/numExp; Display average, maximum, and minimum effectiveness. // End of algorithm ©Aditya Mathur. CS 180. Fall 2011. Week 631

32 9/26/2011 Live demo. ©Aditya Mathur. CS 180. Fall 2011. Week 632

33 Loops: More! 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 633

34 Loops: Why use them? 9/26/2011 Useful to do “same” thing over and over either a fixed or a variable number of times. ©Aditya Mathur. CS 180. Fall 2011. Week 634

35 while loop: Basic structure 9/26/2011 initialize; while (condition){ loop body; } finalize; 1.The loop body is guarded by the condition. 2.Before each iteration, the condition is evaluated. If it is true then the loop body is executed exactly once else the loop is said to terminate. 3.Number of iterations depends on the condition. 4.A loop that never terminates is also known as an “infinite loop” ©Aditya Mathur. CS 180. Fall 2011. Week 635

36 for loop: Fixed number of iterations 9/26/2011 initialize; for( int i=0; i<N; i++){ loop body; } finalize; 1.The loop body is executed N times. 2.Variable i is set to 0. It is incremented by 1 after each iteration. 3.Number of iterations is N unless something drastic happens in the loop body. ©Aditya Mathur. CS 180. Fall 2011. Week 636

37 for loop: Example: Sum the first 10 integers 9/26/2011 int sum=0; for( int i=1; i<=10; i++){ sum=sum+i; } System.out.println(sum); ©Aditya Mathur. CS 180. Fall 2011. Week 637

38 for statement: general format 9/26/2011 for( init; term; iter){ loop body; } init: Evaluated once at the start of the loop term: termination condition, checked at the start if each iteration iter: evaluated at the end of each iteration for( int i=1; i<=10; i++){ sum=sum+i; } sample init term iter ©Aditya Mathur. CS 180. Fall 2011. Week 638

39 Problem: Statement 9/26/2011 Continuously monitor the position of two ground vehicles. The position of each vehicle is available as an (x,y) coordinate. If the vehicles are less than distance d apart then display a warning signal. Stop monitoring when both vehicles have stopped. ©Aditya Mathur. CS 180. Fall 2011. Week 639

40 Problem: Understanding 9/26/2011 How do we get the position: Assume that both vehicles provide this information with respect to an origin. How often should we get the position? Assume every 1 second. What is d? Assume that d is given. How do we know that a vehicle has stopped? Assume that the vehicle has stopped when its two consecutive positions do not change. ©Aditya Mathur. CS 180. Fall 2011. Week 640

41 Algorithm 9/26/2011 Get minimum allowable distance d; moving=true; // Both vehicles moving pos1=get position of vehicle 1; pos2=get position of vehicle 2; while (moving){ compute distance dist; if(dist<=d){ Display warning; } prevPos1=pos1; prevPos2=pos2; pos1=get position of vehicle 1; pos2=get position of vehicle 2; if((pos1-prevPos1)==0){ stop1=true; } if((pos2-prevPos2)==0){ stop2=true; } if(stop1&&stop2){ moving=false; } } // end of loop ©Aditya Mathur. CS 180. Fall 2011. Week 641

42 Algorithm (Graphical) 9/26/2011 Start Stop monitoring? Yes No too close? Display Warning Both stopped? Set end flag YesNo Update vehicle positions No Yes End Wait for 1 second Initialize What should be initialized? ©Aditya Mathur. CS 180. Fall 2011. Week 642

43 Algorithm [Textual] 9/26/2011 do forever { get pulse rate; if the pulse rate is between 60 and 100 then Display “Normal”; else if the pulse rate is<60 then Display “Low”; else Display “High”; Wait for 5 seconds; } ©Aditya Mathur. CS 180. Fall 2011. Week 643

44 Problem 9/26/2011 We are given monthly rainfall data for a region. Write a program to compute the average yearly rainfall in that region. Understand the problem: 1.In what form is the data available? Integer? Float? Input via console? 2.How much data? ©Aditya Mathur. CS 180. Fall 2011. Week 644

45 9/26/2011 Java program for pulse rate monitoring and display. Live demo. ©Aditya Mathur. CS 180. Fall 2011. Week 645

46 9/26/2011 Java program for vehicle collision detection. Live demo. ©Aditya Mathur. CS 180. Fall 2011. Week 646

47 Week 6: September 26-30, 2011 Hope you enjoyed this week! Questions? Contact your recitation instructor. Make full use of our office hours. 9/26/2011©Aditya Mathur. CS 180. Fall 2011. Week 647


Download ppt "CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 6: September 26-30, 2011 Aditya Mathur Department of Computer Science Purdue."

Similar presentations


Ads by Google