week01a - ECE 462 Object Oriented Programming using C++ and...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ECE 462 Object Oriented Programming using C++ and Java Objects and Classes Sam Midkiff smidkiff@purdue.edu 1 Wednesday, August 24, 2011 ECE 462 Object-Oriented Programming using C++ and Java Course Organization and Grading YHL Wednesday, August 24, 2011 Organization and Grading 1 Course Organization YHL Wednesday, August 24, 2011 Organization and Grading 2 Prerequisites • ECE 264. If you have not taken ECE264, please talk to the instructor. • Understand the concept of pointers in C • Know how to write and compile C programs in UNIX-based (e.g. Linux or Solaris) machines, using tools & commands such as gcc, gdb, and Makefile • I will not emphasize syntax. Instead, we will spend more time on how to design and implement non-trivial programs. • Expect to read and write a lot of code -- programming well requires doing it enough that you think algorithmically, and encoding an algorithm in a programming language is second nature YHL Wednesday, August 24, 2011 Organization and Grading 3 Textbook • "Programming with Objects" by Kak, John-Wiley • source code from the book and errata: http://programming-with-objects.com/ • many executable examples about the concepts explained in the book • contains topics that are rarely discussed in other books, such as multiple inheritance • provides frequent comparison between C++ and Java YHL Wednesday, August 24, 2011 Organization and Grading 4 http://www.itap.purdue.edu/tlt/blackboard/ Everything is in Blackboard. Please check it often. YHL Wednesday, August 24, 2011 Organization and Grading 12 Course Outcomes 1. write object-oriented programs of moderate complexity in Java. 2. write object-oriented programs of moderate complexity in C++. 3. understanding of the concepts of inheritance and polymorphism. 4. use template classes and the STL library in C++. 5. overload operators in C++. 6. incorporate exception handling in object-oriented programs. 7. understanding of the difference between function overloading and function overriding. 8. write programs with multiple threads and use synchronization among threads. Passing all outcomes is a necessary (but not sufficient) condition to receive a passing grade (A - D). YHL Wednesday, August 24, 2011 Organization and Grading 17 Check Blackboard for announcements. YHL Wednesday, August 24, 2011 Organization and Grading 18 Grading YHL Wednesday, August 24, 2011 Organization and Grading 19 Grading • • • • • Weekly assignments, class participation and homework, 10 points Group projects, 30 points Individual projects, 30 points Midterms and finals, 30 points (10 points the final, 20 points split between midterms) All exams are open-book, open-note. No collaboration. No electronic devices (including phones) Bring a photo ID for all exams • A: 87 points or higher, B: 75 - 86.9, C: 65 - 76.9 … after normalization by the highest score in class (if < 100). • F: fail any outcome, cheat, do poorly. You will have at least two chances to pass an outcome. YHL Wednesday, August 24, 2011 Organization and Grading 20 Class Participation • Each person can earn 5 points + up to 10 bonus points: You can receive 0.5 point for each of the following items – provide 3 or more questions for an exam (I need to have these at least 48 hours before the exam) – post a meaningful message in a discussion – fill a survey or the course evaluation – submit a programming assignment on time – visit my office during office hours YHL Wednesday, August 24, 2011 Organization and Grading 21 Exams (open book, open note, individual) • multiple choices, short answers, short code segments • “zero-tolerance” of dishonesty: violations will be reported to the associate head of ECE and the dean of students. • Cheaters (exams or assignments) will receive F. • Regrading must be submitted by a written request (or email) within one week after the grade is posted. • You can arrange to take an exam early for good cause. Please contact me as soon as possible. • Taking an exam late will be much harder to get approved. YHL Wednesday, August 24, 2011 Organization and Grading 25 Collaboration and Submitting work • You can discuss lecture, homework, lab, or programming assignments with anyone. You can share code only with your programming partner (if you have one). • You can have one and at most one partner for each programming assignment. All other coursework must be done by yourself only. If you discuss with anyone, please document it in your submission. • The submission strategy will be announced later, but you should ensure your programs run on the MSEE 190/ECN Linux machines. • Having code similar to another project’s code may lead to an F in the assignment and/or the course. YHL Wednesday, August 24, 2011 Organization and Grading 26 Programming Assignments • 4 regular programming assignments: –Java –C++ –C++ ⇒ Java –Java ⇒ C++ –You can do each assignment alone or work with one (only one) classmate. You may change the group mate for each assignment. • You can discuss programming assignments with anyone but you are allowed to share code only with your partner. • If you work in a team, both students must submit the same files + GROUP. YHL Wednesday, August 24, 2011 Organization and Grading 29 Programming Assignment 5 • You (and your group mate) decide what to do. You can choose Java or C++ or both. • Requirements: –object-oriented –an interactive game + graphical user interfaces –networking (required) YHL Wednesday, August 24, 2011 Organization and Grading 30 Questions? YHL Wednesday, August 24, 2011 Organization and Grading 31 I will take a picture of the class and have you identify yourselves at a later lecture in a perhaps (vain) attempt to learn names YHL Wednesday, August 24, 2011 Organization and Grading 52 You are responsible for your own learning and grade. I can guide you, but I cannot learn for you. YHL Wednesday, August 24, 2011 Organization and Grading 57 Your submissions will likely be graded using the machines like those in MSEE 190. Make sure you test the programs at these machines before submission. YHL Wednesday, August 24, 2011 Organization and Grading 58 My goal is to help you learn • It may not be obvious in the classroom, but I will spend a lot of time on this class. My reward for this is that some (and I would like to think all) of you will know significantly more on Dec. 10 about the subject than you do now. My interests are aligned with your long-term interests. I am not your enemy. • I am a human and therefore have limited powers. Therefore I: – – – – may make mistakes. cannot respond to your email immediately. may be in a meeting when you want to talk. has other responsibility, such as writing recommendation letters, committees, seminars, conferences ... • If you make an appointment, make sure we have a set time. When I send you a range of available times we need to decide on one -- you shouldn’t just “show up” at one of the times. • No knows all of C++ or Java. I don’t claim to come close to it. I will, however, try to get a YHL nswers to anything I don’t know in the classroom. Organization and Grading Wednesday, August 24, 2011 59 Communication • Email is the best way to contact me • Please put 462 in the subject line of the email -- it will help it get in the right mailbox and for me to see it. • If you use an email address other than your Purdue address, let me know that address in an email from your Purdue address. • Don’t call and leave a message 21 Wednesday, August 24, 2011 Loudness ≠ Correctness - social interaction 101 • Sometimes, a few students post complaints to discussion. Complaints help no one. If you think something should be improved, give suggestions. • Being loud or dominating a discussion is not the same as being correct. • Distinguish "This is stupid!" from "This can be improved." • If you have a positive attitude, people will be nicer to you. • If you respect others, they will be more likely to respect you. • Try to find answers instead of asking and waiting. But do ask if you cannot find the information. YHL Wednesday, August 24, 2011 Organization and Grading 60 Late Policy • All submissions must turned in the Saturday before exams begin. • Your grades are determined by what you submit, not what you could have submitted. YHL Wednesday, August 24, 2011 Organization and Grading 61 Hard Deadlines • Some people think it would be all right for being late "just two minutes." • In reality, many problems cannot wait for even a minute: –tax report –Y2K –stock trading (4PM closing) –If the CEO of your company is scheduled to give a demonstration in a trade show, the CEO cannot wait for "just two minutes" on the stage. • You have 15 weeks before December 5. Please do not procrastinate. YHL Wednesday, August 24, 2011 Organization and Grading 62 YHL Wednesday, August 24, 2011 Organization and Grading 64 What is an object? 26 Wednesday, August 24, 2011 Now for something technical ... 27 Wednesday, August 24, 2011 ECE 462 Object-Oriented Programming using C++ and Java Objects and Classes Text YHL Wednesday, August 24, 2011 Object and Class 28 Why OO languages? • Earliest languages (Fortran and Cobol) were tailored to specific domains (matrix oriented numerical applications and business processing with record oriented data) – Relatively low level – Built-in types, and operations on those types – Poor support for encapsulation -- a change in the data layout of a data structure could require changes throughout the program. Code making use of the data needed to know how the data was laid out • Algol 60 made control flow easier, messier function/subroutine semantics – good support for structured programming – no goto’s, computed gotos, labels much rarer YHL Wednesday, August 24, 2011 Object and Class 29 Why OO languages? • Early Basics were syntactically and semantically easier to understand – control flow messed up completely with subroutine calls ... $a1 = 42 gosub func1 ... more user code more user code func1: if ($a1 > 0) ... return ... more user code subroutines were inline you could gosub to them or drop through to them • Pascal a rebellion against this -- introduced abstract types (essentially structs and enums in C • PL/1 IBMs attempt at a better language – lots and lots of primitive data types and compiler knowledge of those types – massive compiler, very complex, combined the best (and worst) of Fortran, YHL Cobol, Pascal, Agol Object and Class 30 Wednesday, August 24, 2011 Why OO languages? • Algol 60 mutated into Algol 68, also horrifically complicated • C was a rebellion against both of these and this trend – access to machine level actions (++, +=, *p, *p( ), <<, >> – access to runtime concepts (malloc, longjump, ...) – some attempts at abstraction (struct, enum) – programmer had great power, and great responsibility – common idioms still rely on knowledge of the underlying data structure • fprint(“%d\n”, &i) instead of fprint(i.string( )); p = headP; while (p != null) {/* operate on p */ ...; p = p.next;} • the data in the linked list node pointed to by p is logically unrelated to the fact that it is in a linked list node, but C commingles these in the program logic YHL Wednesday, August 24, 2011 Object and Class 31 This all works fine until ... • You have 5,000 programmers working against the same code base –Read Fred Brooks, The Mythical Man Month –Must program to interfaces (black boxes), not to internal logic –Must be able to believe specs, cannot hope to understand what 5,000 are doing, or talk to them to figure it out • You have a code base of 1,000,000+ lines that you are debugging –OS/360 had 4 or 5 million lines, almost killed IBM –Windows XP had a code base of 45,000,000+ lines •Was a year or so late •Didn’t really phase Microsoft’s revenue stream • Object oriented languages are a way to deal with this complexity by programming to specifications using abstractions and specifications -- program to the problem not to the machine or needs of the compiler YHL Wednesday, August 24, 2011 Object and Class 32 What is an Object? An object can be a “concrete and tangible” entity that can be separated with unique properties: – you – your book – your car – my computer – Tom – Amy’s computer – your phone – Sam’s digital camera – Otto’s cat ... YHL Wednesday, August 24, 2011 Object and Class 33 What is an object? • An object can be abstract and does not have to be tangible: –Purdue ECE's student database –the email sent by Mark at 9:07AM on 2008/03/22 –the Purdue ECE 462 web page –the song played in WBAA at 7:02PM last night • An object can contain other objects: –a car = wheels + engine + door + windshield + ... –a house = kitchen + bedrooms + living room + ... –a laptop = keyboard + display + processor + ... YHL Wednesday, August 24, 2011 Object and Class 34 Objects' Three Properties • Each object is unique and can be identified using a name, a serial number, a relationship with another object ... • Each object has a set of attributes, such as location, speed, size, address, phone number, on/off ... • Each object has unique behaviors, such as ring (phone), accelerate and move (car), take picture (camera), send email (computer), display caller (pager) • Each object has three important properties: –unique identity –attributes, holds a state –behavior (action), verb YHL Wednesday, August 24, 2011 Object and Class 35 Objects’ Interactions • You (object) press (action) the pedal (object) of your car (object). As a result, your car accelerates (action). • When your phone (object) rings (action) and alerts (action) you (object) of an incoming call (state), you answer (action) the call (state). • You submit (action) homework (object) and it is graded (action) with a score (state). YHL Wednesday, August 24, 2011 Object and Class 36 An Object as a Special Case • A person is an object. A student is also an object. A student is a special case of a person ⇒ A student has all attributes of a person: name, home address, parents ... ⇒ A student has all behavior of a person: eat, sleep, talk ... ⇒ A student has something that a person may not have: –attributes: student ID, list of courses, classmates ... –behavior: submit a homework, take an exam ... YHL Wednesday, August 24, 2011 Object and Class 37 What is a Class? • A class describes the commonalities of similar objects: –Person: you, David, Mary, Tom, Amy ... –Car: your Toyota Camry, his Ford Explorer, Jennifer's Testarossa ... –Classroom: EE170, EE117, EE129 ... –Building: EE, MSEE, Purdue Bell Tower, Hovde Hall... • A class describes both the attributes and the behavior: –Person: name, home ... + sleep, eat, speak ... –Car: engine size, year ... + accelerate, brake, turn ... YHL Wednesday, August 24, 2011 Object and Class 38 Relationship among Classes • A class can be a special case of another class: –Student is a special case of Person –Sedan is a special case of Car –Laptop is a special case of Computer –Computer is a special case of ElectronicMachine ⇒ This is called a "is a" relationship. –any Student object is a Person object –any Sedan object is a Car object –any Laptop object is a Computer object –any Computer object is an ElectronicMachine object YHL Wednesday, August 24, 2011 Object and Class 39 Class and Object • An object is an instantiation (i.e. concrete example) of a class: –an object is unique –a class describes the common properties of many objects • An object A may contain an object B. This must be described in A's class. We can say that one class "has a" class. • For example, an employee “has a” salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class. YHL Wednesday, August 24, 2011 Object and Class 40 Encapsulation • An object can hide information (attributes) from being manipulated by or even visible to other objects: A person's name is given once when the object is created. This attribute is visible but cannot be changed. • An attribute may only be modified via restricted channels to maintain consistency. A person's address and phone number must be changed together when this person moves. YHL Wednesday, August 24, 2011 Object and Class 41 ECE 462 Object-Oriented Programming using C++ and Java Inheritance and Polymorphism YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 42 Inheritance = "Is A" • Any Student object is a Person object. Student class is a derived class of Person. Person is the base class. ⇒ Person is more general, with fewer attributes and behaviors. ⇒ Student is more specific, with more attributes (school, major) and behaviors (submit homework, take exam). • Any TabletPC object is a Computer object. TabletPC class is a derived class of Computer. ⇒ Computer is more general. ⇒ TabletPC is more specific, with more attributes (battery lifetime) and behavior (close or turn the screen) YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 43 Derived Class • A class may have multiple derived classes: –Car: Sedan, Truck, Sport Utility Vehicle, Sport Car ... –Computer: Laptop, Desktop, Server –Person: Student, Teacher, Father, Mother ... • A derived class may also have derived classes: –Vehicle: Car, Bike ... Car: Sedan, Truck ... –Animal: Bird, Mammal ... Mammal: Dog, Cat ... • Use "base" and "derived" classes. Do not use "super" and "sub" classes. A base class or a superclass is "smaller" (fewer attributes and behaviors) ⇒ too confusing YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 44 Why Object-Oriented? • Object-oriented programming (OOP) is more a more natural way to describe the interactions between "things" (i.e. objects). • OOP provides better code reuse: –commonalities among objects described by a class –commonalities among classes described by a base class (inheritance) • Objects know what to do using their attributes: Each object responds differently to "What is your name?" • OOP provides encapsulation: Objects hide data that are best not visible to other objects or protect data from unintentional, inconsistent changes. YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 45 Interface ≠ Implementation If a behavior is common among classes, the behavior should be available in their base class. However, this behavior may need additional information from derived classes and must be handled in derived classes. –Shape: contains color, lineStyle ... attributes –Shape supports getArea behavior –getArea cannot be handled by Shape since different shapes have different area formulas Shape –getArea must be handled by individual derived classes –getArea must be implemented in derived classes Circle Rectangle Triangle YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 46 Override Behavior • Polygon can support getArea. Polygon • Derived classes (such as Triangle, Square, and Pentagon) can have better (faster) ways to getArea. Pentagon Square ⇒ getArea is implemented in Polygon and Triangle the derived classes. • A Polygon object calls getArea in Polygon • A Square object calls getArea in Square if getArea is implemented in Square. • A Pentagon object calls getArea in Polygon if getArea is not implemented in Pentagon. YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 47 Overriding Base Derived Object Execute Y Y Base Base Y Y Derived Derived Y N B B Y N D B N Y Base Error N Y Derived D N N B Error N N D Error The behavior implemented in a sibling class (such as Square-Triangle) has no effect. YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 48 Class and Object Polygon p1; // this is a comment: p1 is a Polygon object p1.getArea();// call the implementation in Polygon Square s2; // s2 is a Square object p1 = s2; // p1 now behaves likes a square // a Square object is always a Polygon object p1.getArea(); // implementation in Square (if available) // this is an example of polymorphism - the occurence of something different forms But . . . Polygon p1; s2 = p1; // error YHL Inheritance and // a Polygon object may not be a Square Polymorphism object Wednesday, August 24, 2011 49 Fundamental Concepts in OOP • object and class • encapsulation • inheritance • polymorphism YHL Wednesday, August 24, 2011 Inheritance and Polymorphism 50 Java and Qt documentation 51 Wednesday, August 24, 2011 • http:// www.oracle.com/ technetwork/java/ javase/overview/ index.html • The easiest thing to do is to google java download or something similar 52 Wednesday, August 24, 2011 • • Java is a managed language. We will go here next The JRE is the runtime for running programs • The JDK is the development kit for writing programs contains the JRE • You may need this The documentation is what we are now interested in 53 Wednesday, August 24, 2011 Since we know not what we do, lets go here! 54 Wednesday, August 24, 2011 This just may tell us more ... 55 Wednesday, August 24, 2011 Or get it for free You can spend money 56 Wednesday, August 24, 2011 The first is a higher level overview, the second has more details So let’s go here! 57 Wednesday, August 24, 2011 Let’s go here 58 Wednesday, August 24, 2011 59 Wednesday, August 24, 2011 Let’s go here Now let’s go here 60 Wednesday, August 24, 2011 And now here ... 61 Wednesday, August 24, 2011 62 Wednesday, August 24, 2011 63 Wednesday, August 24, 2011 64 Wednesday, August 24, 2011 65 Wednesday, August 24, 2011 66 Wednesday, August 24, 2011 Let’s visit the examples 67 Wednesday, August 24, 2011 68 Wednesday, August 24, 2011 69 Wednesday, August 24, 2011 70 Wednesday, August 24, 2011 71 Wednesday, August 24, 2011 72 Wednesday, August 24, 2011 73 Wednesday, August 24, 2011 ECE 462 Object Oriented Programming using C++ and Java Development Environments Sam Midkiff smidkiff@purdue.edu 74 Wednesday, August 24, 2011 Demonstrations • • • • • • Develop a C++ project in Eclipse Develop a Java project in Eclipse Develop a Java project in Netbeans Compile and execute a C++ project in the Unix shell Compile and execute a Java project in the Unix shell Example program: Person and student and classes 75 Wednesday, August 24, 2011 Setting up an execution environment You can use Netbeans or Eclipse for developing Java or • • • • • • C++ projects. Please remember to use your ee462xxx account in MSEE190.Your personal Purdue account will not work. Do not use the ee462xxx account for any other purpose. After the final exam, the account will be erased and the password will be reset 76 Wednesday, August 24, 2011 Install eclipse on your own machine My own machine is a mac, so I’ll show how to do it there. 77 Wednesday, August 24, 2011 78 Wednesday, August 24, 2011 79 Wednesday, August 24, 2011 80 Wednesday, August 24, 2011 81 Wednesday, August 24, 2011 82 Wednesday, August 24, 2011 It should figure out your OS If not, select it here (windows, mac, linux 83 Wednesday, August 24, 2011 84 Wednesday, August 24, 2011 85 Wednesday, August 24, 2011 Installing Eclipse • The archive unpacks into the default directory • Move it to Applications, or wherever you want to run it from 86 Wednesday, August 24, 2011 87 Wednesday, August 24, 2011 88 Wednesday, August 24, 2011 89 Wednesday, August 24, 2011 90 Wednesday, August 24, 2011 91 Wednesday, August 24, 2011 92 Wednesday, August 24, 2011 93 Wednesday, August 24, 2011 94 Wednesday, August 24, 2011 95 Wednesday, August 24, 2011 96 Wednesday, August 24, 2011 97 Wednesday, August 24, 2011 98 Wednesday, August 24, 2011 99 Wednesday, August 24, 2011 100 Wednesday, August 24, 2011 Close the overview 101 Wednesday, August 24, 2011 Develop a C++ project in Eclipse • See the video linked to from the course web page. 102 Wednesday, August 24, 2011 Three simple programs 103 Wednesday, August 24, 2011 /* TermIO.c */ A C program #include <stdio.h> main( ) { int i; int sum = 0; char ch; } printf("Enter a sequence of integers: "); while (scanf("%d", &i) == 1) { /* sum += i; /* while ((ch = getchar()) == ' ') ; /* if (ch == '\n') break; /* ungetc(ch, stdin); } printf("The sum of the integers is : %d\n", return 0; 104 Wednesday, August 24, 2011 (A) (B) (C) (D) */ */ */ */ sum); A. scanf reads an integer, returns 1 if successful B. Want to continue until a newline character found C. scanf eats white space, and so would devour the newline character, so manually grab the white space D. break out of the loop when a newline is found // TermIO.cc #include <iostream> using namespace std; A. cin and cout are input (output) stream objects that are defined in the std namespace. C++ allows operator overloading. Thus “>>” can be a right shift, or in the case an extraction operator int main( ) { int sum = 0; cout << "Enter a sequence of integers: "; int i; while (cin >> i) { sum += i; while (cin.peek( ) == ' ') cin.get( ); if (cin.peek( ) == '\n') break; } cout << "Sum off the nubmers is: " << sum return 0; } 105 Wednesday, August 24, 2011 // (A) // (B); // (C) << endl; // TermIO.cc #include <iostream> using namespace std; A. How does C++ know what “>>” or “<<“ means? By looking at the types of the operands -- an input (output) stream and an integer. int main( ) { int sum = 0; cout << "Enter a sequence of integers: "; int i; while (cin >> i) { sum += i; while (cin.peek( ) == ' ') cin.get( ); if (cin.peek( ) == '\n') break; } cout << "Sum off the nubmers is: " << sum return 0; } 106 Wednesday, August 24, 2011 // (A) // (B); // (C) << endl; // TermIO.cc #include <iostream> using namespace std; B. (and C.) deal with the fact that the “>>” operator automatically grabs white space. So after extracting an int, cin.peek and cin.get skip over the white space and look for a newline in the next character int main( ) { int sum = 0; cout << "Enter a sequence of integers: "; int i; while (cin >> i) { sum += i; while (cin.peek( ) == ' ') cin.get( ); if (cin.peek( ) == '\n') break; } cout << "Sum off the nubmers is: " << sum return 0; } 107 Wednesday, August 24, 2011 // (A) // (B); // (C) << endl; // TermIO.cc #include <iostream> using namespace std; Note the declaration in the middle of a block! int main( ) { int sum = 0; cout << "Enter a sequence of integers: "; int i; while (cin >> i) { sum += i; while (cin.peek( ) == ' ') cin.get( ); if (cin.peek( ) == '\n') break; } cout << "Sum off the nubmers is: " << sum return 0; } 108 Wednesday, August 24, 2011 // (A) // (B); // (C) << endl; Something interesting about the last example • We used objects and overloading in this example, but we didn’t actually create any classes or objects • C++ allows programs to be written with functions outside of classes • Java does not allow this 109 Wednesday, August 24, 2011 // TermIO.java A Java program import java.io.*; class TermIO { static boolean newline;! ! // (A) ! public static void main(String args) { int sum = 0; System.out.println("Enter a sequence of integers: "); while (newline == false) { String str = readString( ); if (str != null) { int i = Integer.parseInt(str); sum += i; } } System.out.println("Sum of the numbers is: " + sum); } 110 Wednesday, August 24, 2011 static String readString( ) { String word = ""; try { int ch; while (( ch = System.in.read ( ) ) == ' '); if (ch == '\n') { newline = true; return null; } word += (char) ch; while (( ch = System.in.read ()) != ' ' && ch != '\n') word += (char) ch; if (ch == '\n') newline = true; } catch (IOException e) { }; return word; } } // TermIO.java import java.io.*; A. The variable newline keeps track of whether or not an newline character has been found class TermIO { static boolean newline;! ! // (A) ! public static void main(String args) { int sum = 0; System.out.println("Enter a sequence of integers: "); while (newline == false) { String str = readString( ); // (B) if (str != null) { int i = Integer.parseInt(str); // (C) sum += i; } } System.out.println("Sum of the numbers is: " + sum); } 111 Wednesday, August 24, 2011 // TermIO.java import java.io.*; class TermIO { static boolean newline;! ! // (A) ! B. The function readString reads an string of numeric characters into a string object C. The standard class Integer has a method (behavior) that converts a string of numeric characters into an integer value. { public static void main(String args) int sum = 0; System.out.println("Enter a sequence of integers: "); while (newline == false) { String str = readString( ); // (B) if (str != null) { int i = Integer.parseInt(str); // (C) sum += i; } } System.out.println("Sum of the numbers is: " + sum); } 112 Wednesday, August 24, 2011 static String readString( ) { // (D) String word = ""; try { int ch; while (( ch = System.in.read( ) ) == ' ');// (E) if (ch == '\n') { // (F) newline = true; // (G) D. The method readString is a return null; // (H) } static method. This means that it word += (char) ch; // (I) is associated with the class, and while (( ch = System.in.read()) != ' ' not a particular object in the && ch != '\n') // (J) word += (char) ch; // (K) class. if (ch == '\n') newline = true; // (L) } catch (IOException e) { }; return word; } } 113 Wednesday, August 24, 2011 } static String readString( ) { // (D) String word = ""; try { int ch; while (( ch = System.in.read( ) ) == ' ');// (E) if (ch == '\n') { // (F) newline = true; // (G) return null; // (H) } E. This loop strips off leading word += (char) ch; // (I) spaces. What we return should while (( ch = System.in.read()) != ' ' just be numerals. && ch != '\n') // (J) word += (char) ch; // (K) F. If a newline character is if (ch == '\n') newline = true; // (L) enountered, } catch (IOException e) { }; G. the variable newline is set to return word; } false and H. readString returns null 114 Wednesday, August 24, 2011 static String readString( ) { // (D) String word = ""; try { int ch; while (( ch = System.in.read( ) ) == ' ');// (E) if (ch == '\n') { // (F) I. If an numeral 0 - 9 is newline = true; // (G) return null; // (H) encountered, we append it to } the variable word word += (char) ch; // (I) J. and check the next character, an while (( ch = System.in.read()) != ' ' && ch != '\n') // (J) and if it is not a newline and not word += (char) ch; // (K) a space if (ch == '\n') newline = true; // (L) } catch (IOException e) { }; K. it is also appended to word. return word; L. Check to see if the character } that ended the loop for J is a newline } 115 Wednesday, August 24, 2011 static String readString( ) { // (D) String word = ""; try { int ch; while (( ch = System.in.read( ) ) == ' ');// (E) if (ch == '\n') { // (F) newline = true; // (G) return null; // (H) } word += (char) ch; // (I) What if a character other than a while (( ch = System.in.read()) != ' ' ‘\n’, a space or a numeral is found? && ch != '\n') // (J) word += (char) ch; // (K) if (ch == '\n') newline = true; // (L) It will be appended to word and } catch (IOException e) { }; returned. return word; } } 116 Wednesday, August 24, 2011 // TermIO.java import java.io.*; class TermIO { static boolean newline;! ! // (A) ! public static void main(String args) { int sum = 0; System.out.println("Enter a sequence of integers: "); while (newline == false) { String str = readString( ); // (B) if (str != null) { int i = Integer.parseInt(str); // (C) sum += i; } } System.out.println("Sum of the numbers is: " + sum); } 117 Wednesday, August 24, 2011 When the nonnumeric character (say ‘a’) is returned in a string (say “012a43”) parseInt will not be happy. It will thrown a NumberFormatExcepti on that can be caught by an exception handler. More about this later, but it is a very convenient way to handle errors. By the way, NumberFormatExcepti on is a class. 118 Wednesday, August 24, 2011 119 Wednesday, August 24, 2011 120 Wednesday, August 24, 2011 121 Wednesday, August 24, 2011 122 Wednesday, August 24, 2011 123 Wednesday, August 24, 2011 124 Wednesday, August 24, 2011 125 Wednesday, August 24, 2011 126 Wednesday, August 24, 2011 127 Wednesday, August 24, 2011 128 Wednesday, August 24, 2011 129 Wednesday, August 24, 2011 Course Account and Tools • Each student receives a class account "ee462xxx" in Blackboard. • Please change the password by > ssh ee462xxx@shay.ecn.purdue.edu > passwd • Use the account in MSEE 190 Lab (or any ECN Linux). • Many tools (or newer versions) are available for your ee462xxx accounts. Do not use your personal Purdue account. • Type "more /home/shay/a/sfwtools/public/README" • Put "source /home/shay/a/sfwtools/public/settings" in your ~/.cshrc (if you use csh or tcsh) • The videos are recorded in Windows but the programs can run on both Linux and Windows. YHL Wednesday, August 24, 2011 Organization and Grading 28 You should have ECE462 in your Blackboard already. YHL Wednesday, August 24, 2011 Organization and Grading 33 YHL Wednesday, August 24, 2011 Organization and Grading 34 YHL Wednesday, August 24, 2011 Organization and Grading 35 YHL Wednesday, August 24, 2011 Organization and Grading 36 Notice the due date. YHL Wednesday, August 24, 2011 Organization and Grading 37 YHL Wednesday, August 24, 2011 Organization and Grading 38 YHL Wednesday, August 24, 2011 Organization and Grading 39 YHL Wednesday, August 24, 2011 Organization and Grading 40 YHL Wednesday, August 24, 2011 Organization and Grading 41 YHL Wednesday, August 24, 2011 Organization and Grading 42 YHL Wednesday, August 24, 2011 Organization and Grading 43 YHL Wednesday, August 24, 2011 Organization and Grading 44 How to Resubmit YHL Wednesday, August 24, 2011 Organization and Grading 45 YHL Wednesday, August 24, 2011 Organization and Grading 46 YHL Wednesday, August 24, 2011 Organization and Grading 47 YHL Wednesday, August 24, 2011 Organization and Grading 48 YHL Wednesday, August 24, 2011 Organization and Grading 49 YHL Wednesday, August 24, 2011 Organization and Grading 50 ...
View Full Document

This note was uploaded on 02/19/2012 for the course ECE 462 taught by Professor Samuelmidkiff during the Fall '11 term at Purdue University-West Lafayette.

Ask a homework question - tutors are online