come back and find CountChars 341-4677, Gamma 4; damarcus10@hotmail.com 9/8/98 ====== [test coming up Thursday...more of a quiz] Six symbols for flow charting: circle: begin / end diamond: decision rectangle: process expansion block: [square with two lines ; sidebars] case: [more of a five sided diamond] parallelogram: input / output ...moving out into a method... in other languages, that could be a function, or a proceedure. case structure: a whole lot of things together...which later make a choice. algorithm: a finite set of clearly stated steps which will eventually terminate showing a desired outcome. first...we want to setup an algorithm. Then, we want to go back, make it more efficent, streamline it, make it easier to maintain, and make it better. **KNOW** POLYA ===== understand design implement evaluate SDLC ==== requirement specs analysis design code implement test DECISION STRUCTURE ================== ribbon problem: 1) is there a ribbon? 2) determine color: is it red? -> put in red pile is it blue? -> put in blue pile [else, just do this..] 9/8/98 [afternoon] [page 8] look it up... type in sample program public static void main (String [] args) { <<-- first line of exe code Capitol letters define CLASSES. there are UP-TO 5 parts of a class: [you don't need all 5 in every class] class variables class methods instance variables instance methods constructor every java program needs a class. System.out.println ("Hello World"); out is acting on System...as a class...et cetera LOOPS ===== (WHILE) with a while loop - it's possible you'll never execute. it asks for the condition FIRST. may or may not execute at all. (DO / WHILE) whith a do/while look, you do the work first, then check to see if you have to do it again. always must execute at least once. sample pseudocode: "compute an average" - for 30 students 1.0 input data for first student 2.0 while....(there are students) 2.1 process student 2.2 output results 2.3 get data for next student (goto while statement) for scores: 2.1 Process Student 2.1.1 Compute Sum (score 1 + score 2 + score 3) 2.1.2 Compute Mean (sum / 3.0) Homework: You are going to fence your back yard. The fence boards are 6 inches wide (.5 feet) The cost of 1 board is $1.25 How much will your fence cost? 9/10/98 ======= Requirement Specifications: A. Inputs B. Outputs C. Assumptions D. Formulas E. Problem Description (1-2 sentences) Inputs: Length of Fence Width of Fence Length of House (-) Output: Perimeter of Fence Number of Boards Cost of Fence Assumptions: Input will be positive in range of say 1-200 feet for deminsions. Error trapping will be done. (done in a loop) Formulas: 2W*2L-house length number of boards (perimeter / board width (.5) cost of fence=number of boards * cost of board Problem Description: We wish to fence in the backyard of a fence. We're going to exclude the actual house space and subtract that from the actual length of the fence. ANOTHER EXAMPLE of requirement specs: Write a program to input your distance from a town and the constant speed you are traveling towards that town. Calculate and output the time it will take you to arrive at the town: Inputs: Distance your're traveling Speed you're traveling [MPH] Output: The amount of time it will take you to get from point a to point b. (measured in hours) Assumptions: Lower Limit: 1 ; Highest Limit: 4000 [distance] Distance, speed, and time will be positive. We'll do error checking for this. Lower Limit: 1 ; Highest Limit: 70 [speed] Formulas: distance/speed=time Problem Descrition: blah...blah...blah...blah...blah...blah... bla-bla blah...blah...blah...blah...blah... (part of 9/15) X | | Y =================== 0 4000 x = lower bound y = upper bound LOOPS ===== **ALWAYS USE THIS** WHILE LOOP [good at validating data] 0 or more times 1) read the value 2) check the value 3) if value does not fit requirements, post an error message if it does, exit 4) ask for another value 5) goto 2 DO-WHILE LOOP 1 or more times - test at the end 1) read value 2) if the value does not fit requirements, post an error message otherwise, continue along normal operation 4) actually chck to see if the data is valid ...more later... 9/15/98 ======= quiz on mod 2 -- thursday synthetic and analytic problems Synthetic problems: You know the input and you know the process You have to use the process to locate the output...this is very similarly related to cooking. Analytic problems: Most of the problems in CIS120 are of this type. You initially know your input and your output...you have to define how to get from one end to the other - logically. two ways to document an algorithm - flowcharting and pseudocode. three control structures: ========================= sequence ========= | t= | | d/r | | | ========= selection decision statement... T- /\ /a>\F - - | \b / | \/ | | ==== | | \/ loop T- /\ /a>\F - - | \b / | \/ | <=======| | ==== | | | | | \/ | | again? | ========= | | t= | | | d/r | | | | | ========= | ==================== more on flowcharting... DECISION STRUCTURES =================== GPA == 4.0 -> president's list GPA >= 3.75 -> dean's list GPA >= 3.50 -> chair's list GPA < 2.00 -> probation GPA < 1.00 -> suspension if gpa is greater than 4.0 set value=error goto start if gpa is equal to 4.0 set value=president if gpa is greater than or equal to 3.75 set value=dean if gpa is greater than or equal to 3.50 set value=chair if gpa is equal or less than 2.0 set value=probation if gpa is less than 2.0 set valie=suspension i.e. - gpa < 2.0 && gpa > 1.00 Tuesday Afternoon.... [9/15/98] ===================== page 67...lines 10-11-12-13 - type them in very carefully in this program, we're calling up some initial values.. these are variables...and on the hour variable, we're going to INITIALIZE it. :) Java does __NOT__ automatically initialize ANY variables... [the book incorrectly tells us it does]. If you were to view the contents of any of those variables, you would get RANDOM GARBAGE. Most languages do NOT initialize varaibles to 0. ==8 primitive data types=== 4 integer types: byte -- -- 1 byte [ -128 <-> 128] short - -- 2 bytes [-32768 <-> 32767] int -- -- 4 bytes -2 billion <-> 2 billion long -- -- 8 bytes much much larger. ;) 2 real types float - -- 4 bytes double -- 8 bytes 1 boolean boolean -- 1 bit 1 character char - -- 2 bytes int long 9/22/98 ======= Arithmetic Operations: Order of Precedence: [Highest -> Lowest] [Always process in order from left to right] (1) () Parenthesis (2) *,/,% Includes Modulus Arithmetic [modulus helps to determine things like leap years ; [try to devide by 2, can help determine if it's a leap year] Example: 4 / 1998 = R of 2 (3) + , - Add, Subtract (4) <, > , <= , <= Relational Operators (5) == , != Equality Operators (6) && = Logical AND (7) || // Logical OR Operators onf the same prcendence level, such as *, / , % are evaluated from left to right. Built-In Operations on numberic types Operators: -,+,*,/ Operands: BOTH INT YIELDS INT 6/2->3 5/2->2 Because both of these guys are integers, you drop the additional portion of the decimal answers. [Truncated answer] BOTH FLOATS YIELDS FLOAT 6.0/2.0 -> 3.0 5.0/2.0 -> 2.50 MIXED YIELDS FLOAT 6.0/2 -> 3.0 5.0/2 -> 2.50 6 % 2 = 0 5 % 2 = 1 (modulus basically determines the remainder) *****ONLY WORKS ON INTEGARS...do not do it on a flat.***** hours (float) = distance (int) / speed (int) when you do this....distance (int) / speed (int) will produce an INT...although hours is a FLOAT. the type is in parenthesis, not the variable [to convert] (in C++, it's the other way around) ASSIGNMENT STATEMENTS ===================== float variable = int value (no problem!) int variable = float value (truncation!) [you'll have to do a cast on this] cast = hours = (float) distance / (float) speed; //for that statement only, take the variable and temporarily //convert it to a float and assign it to the hours variable. //only for this statement, it is making it a float so it can //do the computation and make hours a float. later on, it will //appear normal - its ONLY for this statement. Examples: 7/2/4 |-| 3 | 3 / 4 |-| 0 4.0/3.0 | - | 1.3334 [if it's an I=4.0/3.0 ; it's truncated!] (ALWAYS do the arithmatic, THEN store the value) UUUUUUGGGGGGGHHHHHHH========LOGIC========UUUUUUUUGGGGGGGGGHHHHHHHHH Example 1: 1<5&&4==4||7!=8 step 1: is 1 < 5 true. step 2: is 4==4 true. step 3: does 7 != 8? true. step 4: T AND T gives a TRUE step 5: TRUE OR TRUE gives me a TRUE [aaaaauuuuuuggggggghhhhhh!!!!!!!!] Example 2: 3+2>4&&6/3==2 step 1: 3+2=5 step 2: is 5 > 4 true. step 3: is 2==2 true. step 4: true and true TRUE. Example 3: (7==4) || (4!=5) (false) || (true) true. Representational Errors: INTEGERS ======== Overflow - the loss of data as a result of attempting to store an integer larger than the maximim possible with number of bits allocated. Example: Integer data type allocates 4 bytes of memory. This designation will store any number in the range of 32767 to -32768. Any attempt to store a number greater or smaller will result in overflow. [C++ = 2 bytes, java = 4 bytes] (long int will be 9 bytes, holds 64 bits - LONG INT) Student Numbers are 120,000+ [MUST be long int] (ie, 116814] FLOATS ====== Roundoff - Occurs when more than the specified number of bits is needed for the mantissa. (in our case, more than 24 bits, approximately (+-) 16 million) Underflow - Occurs when more than the specified number of bits is needed for the exponent. (In our case, more than 6 bits, approximately) (+,- 64) [afternoon, 9/22/98] IN GENERAL ========== CANCELLATION ERROR Of X is much larger than Y, then X+Y may have same value as X. For example, (in some computers), 1000.0 + 0.0001234=1000.0) OTHER REPRESENTATIONAL ERRORS: 1/3 Cannot be represented with terminating decimal (1.33333...) 0.1 Cannot be represented precisely when using binary number system. 9/24/98 ======= primitive data types: integer ======= byte - 1 byte - 2^7 ; -128-127 short - 2 bytes - 2^15 - -32768 - 32767 int - 4 bytes - 2^31 - -+2 billon long - 8 bytes - +- 2^63 - real ==== float - 4 bytes - 7 decimal places - +- 10^38 double - 8 bytes - 15 decimal - - 10^350 place boolean ======= boolean - 1 bit t=1, f=0 character ========= 2 bytes...such as "A" constant (const) ================ final CLASSES ======= 1. Package [statement] (OPTIONAL) -- a group of related files. If you have a package, it must be your first executable line. package packageName 2. Import [statement] -- (OPTIONAL) -- 3. Class Definition or definitions class ClassName - generic public - can be accessed "outside the class" private - only guys within this package can get into the files protected 5 class components: class variables > class methods > static [you have a CLASS] constructor - EXACTLY same name as the class. instance variables instance methods non-static [you have an INSTANCE] public static void main ^^ -- class method Example Class: HumanBeing class var counter class method showCounter HumanBeing janet=new HumanBeing; int age; int weight; /> Make New Object / Constructor Class -->> Instance Var \ Instance Methods \ Hold Methods -> Class Var Class Methods purpose of a constructor: initialize new objects of the class 9/24/98 ======= Selection / Decision A decision structure (or selection structure) is part of a flow chart o a code segment that causes a choice to be made. This is a branch in the execution. After one of the branches is selected, the execution resumes on a common path (ie - a join in the flow chart). This branching may be to achieve theh effect of "do something or do nothing") [an if-then construct] or to achieve a "Do one of two possible things" [an If-Than-Else construct]. 10/6/98 ======= Mod 4 Program #1 Page 100, #27 Due Tuesday 10/13 afternoon class file AND java file Drop Date is FRIDAY =================== MyClass X; sets up a varabile called X as type "myclass" X=new MyClass () ; (x points to the object ; it's an object reference) ===this is a call to the constructor=== could use: X=new MyClass ("Kemp", 4.0); ~~~ -- constructor (instance variables might be "name" or "gpa") "new buffered reader" - actually a call to the constructor of "buffered reader" In Class Lab ============ Problem Statement: Ask the user to input two test scores. Compute and output the avera rackets if (temp < 20) //remember braces here wear sweater; wear coat; } //end if Examples: 1) String response System.out.print ("Do you want the answer? Y/N"); response=Keyboard.readLine(); if response=("YES") System.out.println ("The answer is..."); 2) Report Balance (if-then-else simple statement) if (balance > 0) System.out.println ("You now owe $" + balance) else System.out.println ("Your balance is paid in full."); 3) If-then-else with simple statemenets if (your number % 2) = = 0 System.out.println ("Your number is even"); else System.out.println ("Your number is odd"); 4) If then else with compound statement if (your number >= 0) System.out.println ("In fact your number is positive"); else system.out.println ("Your number is zero."); } //end else 5) if (userAnswer equals ("yes") { //code for yes answer } // end if // code for no answer } // end if 6) //computer grade average if (grade average >= 90.0) System.out.println ("You earned an A!"); else ... if (gradeAverage >= 80.00) System.out.println ("You earned a B!"); else if (gradeAverage >= 73.00) System.out.println ("You earned a C!"); else if (gradeAverage >= 55.00) System.out.println ("You earned a D!"); else System.out.println (Study Harder, You've Failed!); Boolean Expressions... Example... 1) Boolean Finished code that sets finished to true if (finished) //code for finished else //code for not finished.... 2) if (gradeAverage >= 90.0) //boolean expression is a rational expression //code for A students else //code for non a students another example... if ((gradeAverage >= 80.0 ) && gradeAverage < 90.0) System.out.println (Welcome to National Honor Society); 10/8/98 ======= PROGRAM DUE TUESDAY: ====================================================================== Page 110 - #27...program due TUESDAY [about a commission] A sales person earns a commussion on the value of sales. Figure 3.9 shows the scale of the commission. Write a program to input a figure for the value of the sales, and then calculate and output the commission value of sales commission 1-999 1% 1000-9999 5% 10000-99999 10% ====================================================================== Additional program due NEXT Tuesday [not the 12th, but the 19th] Water treatment program....should require extra...thinking. ;-) "The dreaded dangling else..." Problem: Given the code below, what is printed if x=200? if (x < 100) if (x < 50) System.out.println ("Hello."); else System.out.println ("Bingo."); Answer: nothing. :) Solution: If we want that ELSE clause to bind to the first IF, then we must close the second IF statement. Two solutions: Solution 1: if (x < 100) { if (x < 50) System.out.println ("Hello."); } // end if else System.out.println ("Bingo."); Solution two: if (x < 100) { if (x < 50) System.out.println("Hello"); else; //do nothing, but closes second if else System.out.println("Bingo"); includes a dummy else... 10/13/98 ======== remember... Arithmetic Operations Order of Precedence Highest to Lowest MDAS (multiplication, division, addition, substraction) 1) () Parenthesis from inside out 2) */,% 3) +,- 4) <,>,>=,<= Relational operations 5) ==, != Equality operations 6) && Logical AND 7) || Logical OR sample program: Ask the user to input two test scores and output the average and tell the user if it is a passing grade. Input: 2 test scores, (float) Output: average, (float) a literal (message) Assumptions: data is valid (positive from 0-100) Formulas: average = (scrore1 + score2)/2 Facts: Passing grade is >=73.0 switch statements: a switch is a special form of an if then else statement. it requires special situtations: 1) Must have ordinal data (no floats or strings) integer or char. 2)must only be equality switch (variable) { case x1: do something; break; case x2: do something; break; default:(optional) do something; } SWITCHES......... You can only do a switch with INT data or CHAR data. 10/15/98 ======== Sequence Selection Loop All of these things are to be used in solving problems. You've even got pre-test loop and post-test loops... When a loop is drawn in a flowchart, it's a "cycle". posttest loop - do while pretest loop - for loop, while loop must put instructions in a do/while loop in {'s and }'s while (true) - with a boolean expression example - while (A > b) inside loop you must change the while (a > b) - otherwise, you'll have a completely INFINATE loop! another -- do { } while (boolean) you'll do this once reguardless......[the do] ; then you test after you execute once... for loop - has a specific format.... for (ctr=1, ctr < 5;ctr++) { } then... int sentinel = -1; get acct # while (acct # != sentinel) { get acct # } ... . .. [more code] for (int ctr=0; ctr>=lastvalue;c--) ==or== (ctr >= lastvalue && (finished)) 10/20/98 ======== Loop - Repetition / Iteration A looping structure creates a cycle (loop) in the directed graph we will call the flowchart. We will deal with three varities: while-loop, do-while, and a for loop (continued loop). Each of these allows a block of code, the loop body, to be executed more than once. How many times does each execute the loop body? Loop Kind Minimum Executions Maximum Executions Exit Criteria ========= ================== ================== ============== While 0 none boolean=false do-while 1 none boolean=false for-loop 0 decided at entry "n" exit bound reached Exit criteria checked before loop body in while and for loops, thus leading to the possibility of zero execution of the loop body. A boolean expression controls the iterative process in the cases of the while and do=while loops. It is the user's responsibility to be sure that "something" occurs in the loop body that changes the system state so that "eventually" the exit criteria of the loop will be met. Examples of these changes: a) a file is being read with the loop existing on end-of-file. b) some variable is being changed and the loop exists when it reaches a specified value. Failure to modify the system state in some fashion that leads to the exit criteria being met leads to an infinate loop. [not good!] :) Three steps to successful looping... 1. Loop Control Variable (LVC) must be initialized price to test in loop. 2. LCV must be updated within each execution of the loop. 3. The loop should eventually reach a state where the LCV meets the exit condition and the loop is exited. ***use this first***[successful loops]***use this first*** 1. init your loop control variable 2. test loop control for exit 3. update loop control Certain kinds of situations occur in programming. We call the general structure of the code to handle these situations a TEMPLATE. For example, consider the situation where we read a file or get user input until a specified value is found. That value is called a sentinel value. The code template for this situation is: a. get first data value b. while (currentValue != sentinelValue) c. process the currentValue d. get next data value [updates value for loop test] e. end while loop Java syntax for a while loop while (boolean expression) statement; OR while (boolean expression) { statement 1; statement 2; ... } // end while 10/20/98 - afternoon ==================== Yet another kind of situation is to perform some task a specified number of times, where we know how many times to do the task by the time we arrive at the loop. the code for this template is: a. code that would determine upper bound of looping b. count=1; c. while (count has not reached the upper bound) d. do the process for the count-time (first, second, third, et cetera...) e. increment count f. end while loop when doing a counter, if you wish to do: 0 -- be sure to use < 1 -- be sure to use <= ...Many programs require the user to input valid data defined as being one of a set of values or as being in a specified range. The process of checking the correctness of the inputs is called VALIDITY CHECKING. In the case of bad input, we usually loop until the input is acceptable. The code template for this kind of activity would be: a. ask for input [INITIALIZE] b. get first version of input c. while (input is NOT valid) [TEST] d. give an error message e. ask for input again f. get new verson of input [UPDATE] g. end of while loop 10/22/98 ======== A variation of the while loop, used when we know that we must execute the loop body at least once, is the do-while loop. The do-while loop is a post test loop. Its syntax is: do statement while (loop criteria) do { hmm. hmm. } while (loop criteria) For example, the data validation program presented earlier was shown using a while loop. We can now present the same problem using a different code template and different code. a. start loop b. ask user for input c. get user input d. if (input is NOT valid) e. error message f. while (input is NO valid) Another kind of scenario that arises is the control of loops by flags (boolean variables used for control purposes). In such a case, we actually may do the loop criteria checking within the body of the loop and set a flag when the required criteria has been met. Doing it this way leads to loops controlled by statements such as 'while (myFlag) {...} or while {!MyFlag} {...} where myFlag is basically a boolean variable). Often in the "middle" of an execution of the loop body, we discover that: A) we do not need to execute the rest of the loop body and b) that we are now finished with the loop itself. Consider the following code template for this kind of processing. a. finished=false b. while (!finished) { c. first part of loop body d. if (some criteria) e. finished=true; f. else second part of loop g. end of while loop another pretest loop - counting loop Counting loops are also pretest loops in which a counter is initialized, updated and checked to see if it has reached a terminal value. Java has a more convenient notation for this concept. The notation is for the for loop. The general syntax of this structure is as follows: for (initialization clause; loop criteria; step clause) { statement; statement; } // end of for loop ** tidbit ** for some reason, the letters i,j,k have always been used for c counting loops. The "+=" operator is being used to imply a missing operand (mainly the variable on the left hand side) In a similar fashion: long form short form ========= ========== total=total-newvalue total=new value total=total*newvalue total*=new value Thus incrementing by one could also be achieved by i += 1; The following while loop: count=1; while (count <= 20) { loop body count ++ } //end while can be replaced nicely by the following for loop for (int count=1 ; count <= 20 ; count++) { loop body } 10/27/98 ======== Quiz thursday know how loops work read definitions TRY - this is something where we attempt to use something (hence TRY) if it works; great...if it doesn't, well, here's how to handle it. try { something or other... } catch { handle exception } exception is a keyword in java. 11/2/98 ====== method: function, procedure, sub routine a block of code separate from the main program. main reasons to use methods: reuse, and maintenance methods consist of: < method header > < method body > visibility==public, private, protected, nothing, ==who can read this program. static or instance>> static==class method no static = instance method return type>> int, float, double, byte, short, long, char, boolean, String, , void (nothing) ==addEmUp ==method does not always require parameters--formal parameters method headers: int public static double addEmUp arguement class method etc. not static intance method private protected 11/10/98 ======= can use string tokanizer to count the words. example provided in the handout. "Abed.length()" - length of a word? Abed.charAt(X) -- X = position Anytime you hit a ! or ? or . - subtract 1 char [since java starts counting from 0] length-1 this program does some cool stuff :) required to write 3 or more class methods as part of your solution. one class method (main) number of words / number of sentences {divison} - average words come back and find CountChars sepeate methods...use /==========================/ alias - means another name for the same data piece. static - means CLASS VARIABLE!! if you don't do theFile.newLine(); - you get continuous data ; no line feeds global variables are NOT good to do. it means everyone in this class knows them. private means they're known only in this class. two words when talking about variables: scope (where is it known?) lifetime (for how long is it known?) data stack... when (currentLine != NULL) -- end of line / file main calls process which calls: (driver module) compute line compute etc longesttoken tokencount 11/12/98 ======== inside this new program, filesdemo, whatever, you need to have: write output to output file (non blank lines) count lines (non blank lines) sentences words (based on punctuation) ; keep running total of length average caps token.length is a built in feature token.countTokens is a built in feature aWord.length() -1 == '.' || == '?' == , if so, increment sentence counter by 1. aWord.charAt(aWord.length()-1) if at end of word length, you have a punctuation mark, you need to subtract one. can use this application to actually write and count number of characters for a community billboard ad. ;-) java will return accurate length, by the way. (it'll ignore the 0) using aWord.length()