Upgrade to Pro — share decks privately, control downloads, hide ads and more …

lecture04.pdf

Avatar for William Albritton William Albritton
August 13, 2014
120

 lecture04.pdf

Avatar for William Albritton

William Albritton

August 13, 2014
Tweet

Transcript

  1. Memory Upload • Escape sequences • Writing to a file

    • Spaghetti code • Bento code • Grocery list
  2. Introduction • ICS 211: Introduction to Computer Science II 

    William McDaniel Albritton • Leeward Community College • Mathematics and Natural Sciences Division • Information and Computer Sciences Department
  3. Escape Sequence • To output certain characters within a string,

    use a backslash character (\) before a special character  double_quote = \"  single_quote = \'  newline = \n  tab = \t  backslash = \\
  4. Writing to a File • Need these 3 import statements

    at top of program import java.util.Scanner; import java.io.PrintWriter; import java.io.FileNotFoundException;
  5. Writing to a File • PrintWriter constructor needs a String

    for a parameter  Name of the file, if in current directory • "myFile.txt"  Or full name of path to the file • "C:\ics111\progs\myFile.txt"  1st command-line argument is file name (commandlineArguments[0])
  6. Writing to a File • PrintWriter constructor either creates a

    new file if it does not exist, or overwrites an existing file  Must have a try-catch block, as the PrintWriter constructor will throw a checked exception if the path to the file is incorrect, or if the file is open  See next slide for example code
  7. Example Code PrintWriter writeToFile = null; try { writeToFile =

    new PrintWriter(args[0]); } catch(FileNotFoundException e){ System.out.println("Error!"); }
  8. Command Line & jGRASP • To use command line arguments

    in your program on jGRASP 1.On the top menu, click Build 2.On the drop-down menu, click Run Arguments 3.A Run Arguments text field will appear at the top of the screen 4.Type your command line arguments into this text field
  9. Example Program • See WriteToFile.java  Writes to a file,

    which has the same name as the 1st command-line argument (commandlineArguments[0])  To make the program easier to read, the main() method’s array parameter is commandlineArguments, not args  If no arguments are entered, then the program ends before writing to a file
  10. Example Program • See WriteToFile.java  Note that out of

    System.out is of class PrintStream, which has many methods which are similar to PrintWriter, such as print() and println()  For file names, use fileName.txt, so it is easy to view the files
  11. Putting It All Together • Now we can write a

    program that does something!  We can use arrays & file I/O to implement a grocery list  Think of a grocery list that you write on a sheet of paper before going to the grocery store
  12. Spaghetti Code • “The term spaghetti code is universally understood

    as an insult. All good computer scientist worship the god of modularity, since modularity brings many benefits, including the all-powerful benefit of not having to understand all parts of a problem at the same time in order to solve it.”  Dr. David Clark, Computer Scientist at M.I.T.
  13. Use Methods! • In other words, do NOT put all

    of your code into the main() method  This will make your code harder to write, harder to read, and harder to debug • You need to think about how to divide a problem into logical parts  These logical parts will become your methods
  14. Bento Code • In other words, do NOT write ramen,

    saimin, or yakisoba code • Instead, you should divide your code into methods, just like a bento lunch box, which divides the food into nice, little, cute, portions…
  15. Grocery List Problem • Create a program that models a

    grocery list  Think of a grocery list on a sheet of paper that you usually write down before going to the grocery store  Let’s break this problem down into logical parts
  16. Grocery List Behaviors • Need to implement several methods (behaviors)

    for our grocery list 1. Read grocery list from a file 2. Add a grocery item 3. Delete a grocery item 4. Display the grocery list 5. Write the grocery list to a file
  17. Grocery List Objects • Need to manipulate several variables (objects)

    for grocery list 1. Input file 2. Output file 3. Grocery list array 4. Size of grocery list
  18. Outline of Problem • We can now write an outline

    solution to our grocery list problem, by writing methods stubs  Later on, we will come back and fill in the code for each method stub • This is an example of “not having to understand all parts of a problem at the same time in order to solve it”
  19. Changes in the Plan • “The best-laid plans of mice

    and men often go awry” – Robert Burns • While writing the program, I added another method to display the menu  Did not exactly follow original outline • When you write programs, you may think of new methods to add on the fly as well
  20. Example Code • See GroceryListProgram1.java  Read the comments that

    explain the methods (behaviors) and variables (objects) used in the program  This is still a rough outline of our solution to the Grocery List problem  Most method stubs display their name, so we can see if the correct methods are being called
  21. Bulletproof Coding • When writing a program, you should always

    check for possible errors in the input data • We do not want our program to crash  The programmer has responsibility for creating reliable programs  The programmer should NOT rely on the user to enter the correct data
  22. Testing Our Code • Try to think of as many

    errors in data input as possible 1. Enter too few command line arguments (runs OK, and has error message) 2. Enter too many command line arguments (runs OK, but needs error message)
  23. Testing Our Code • Try to think of as many

    errors in data input as possible 3. Enter choices out of range (runs OK, but needs error message) 4. Enter choices that are not Integers (program crashes!!!)
  24. Testing Our Code • See GroceryListProgram2.java  We made some

    changes in the code to give user more feedback  Also, added try/catch block, so entering a non-integer does not crash the program
  25. File I/O Methods • The next step is to start

    filling in the code for the other methods • Since we already wrote the code for file input and file output, let’s complete those methods next • We also need to think about the file format that we will use
  26. I/O File Structure • A convenient file format to use

    is CSV (comma separated values)  This is good for storing data in tables  Since a CSV file is a text file, we can use any text editor, and the file is easy to read for our Java program  If we want to be more sophisticated, we can use a spreadsheet application such as Microsoft Excel
  27. Creating a CSV File • A CSV file arranges data

    into tables, so we need to think in terms of rows and columns of data  The first row has the headings for each column of data, each heading separated by a comma (,)  The following rows contain the actual data, each individual data in each row separated by a comma (,)
  28. Creating a CSV File • A CSV file arranges data

    into tables, so we need to think in terms of rows and columns of data  Finally, at the end of each row of data, a newline is used
  29. Example CSV File • See groceries.csv  First, view the

    file using a simple text editor, such as WordPad or NotePad • Note the commas  Then try opening the file in Excel, or some other spreadsheet application • Note that the commas have been replaced by rows and columns
  30. Inchworm Principle • See GroceryListProgram3.java  Again, after we write

    a method, we should test the method with not only good data, but also bad data  Like an inchworm, we need to take small steps when writing a program
  31. More Testing • Test GroceryListProgram3.java with input files groceries.csv and

    badList.csv  The second input file has file errors such as extra commas, missing rows, and extra data  Since method readFromFile() reads a whole line at once, these errors are trivial and do not crash the program
  32. Program Crash! • On the other hand, a file with

    too many rows (over 100 items) crashes the program by throwing an ArrayIndexOutOfBoundsException • We will address this issue later on in the course, as it is easy to solve using linked lists
  33. throws Clause • A throws clause is put in a

    method declaration to indicate that the method might throw an exception • Syntax for throws clause /** Example method * @exception MyException explain */ public static void method() throws MyException { //method's code }
  34. Problem Solving • Computer science is basically about problem solving

    • So how do we solve a problem?  Take 3 main steps 1. Understand the problem 2. Make a plan 3. Implement the plan
  35. Terminology • Like any other discipline, computer science has its

    own “fancy words” (jargon, terminology, vernacular, lingo, gibberish, gobbledygook) • Computer scientists use the word algorithm for the plan that is used to solve a problem
  36. Example Algorithms • Example algorithms from daily life  Take

    train from Makuhari to Nikko  Scuba diving at 5 Caves, Maui  Teach surfing at Baby Queens  Making spam musubi!
  37. Writing Algorithms • When writing an algorithm, you need to

    follow a few rules 1. The algorithm must be a detailed series of steps that will solve the problem 2. The algorithm should be simple, unambiguous, and correct 3. The algorithm can be written in many different ways
  38. Algorithms • As for the remaining three methods, we need

    to design some algorithms to guide the coding for each method
  39. Algorithm for add() 1. Get item’s name from user 2.

    Get item’s number from user 3. Add "name, number" to end of the array 4. Increment (add 1 to) size of the array
  40. Algorithm for remove() 1. Get the row number of the

    item the user wishes to delete 2. Error checking for Integer (try/catch) 3. Error checking for 0 or negative (if) 4. Error checking for too big (if) 5. If no error, remove by shifting all items on the right of deleted item one index to the left (for loop)
  41. Shifting Elements • Delete element #1 (listSize = 4) “natto,

    3" “garlic ,5" “negi, 1" “eggs, 12" null list 0 1 2 3 4 • Array after shift to left (listSize = 3) null
  42. Shifting Elements • Why do we shift elements?  Simply

    deleting the element (by replacing it with null) would leave empty spaces in the array  Instead, we shift all the elements, so they overwrite the element to the left of them  This leaves no empty array spaces
  43. Algorithm for display() 1. Loop through all the elements in

    the array (for loop) 2. Output each element to the screen 1. The first element should display the headings (if statement) 2. All other elements should display the row number, and the item’s name and number (if statement)
  44. Final Version • See GroceryListProgram4.java  This program fills in

    the code for the remaining three methods  Testing and correcting the code has been completed, using both good and bad data inputs, but let me know if you find any bugs
  45. Memory Defragmenter • Special character escape sequences • Write to

    a file • Spaghetti code vs. Bento code • Grocery list problem and solution
  46. Task Manager • Before the next class, you need to:

    1.Do the assignment corresponding to this lecture 2.Email me any questions you may have about the material 3.Turn in the assignment before the next lecture 4.Lighten up!