Share
Embed
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
48 slides
-
Memory Upload • Escape sequences • Writing to a file
• Spaghetti code • Bento code • Grocery list -
Introduction • ICS 211: Introduction to Computer Science II
William McDaniel Albritton • Leeward Community College • Mathematics and Natural Sciences Division • Information and Computer Sciences Department -
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 = \\ -
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; -
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]) -
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 -
Example Code PrintWriter writeToFile = null; try { writeToFile =
new PrintWriter(args[0]); } catch(FileNotFoundException e){ System.out.println("Error!"); } -
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 -
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 -
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 -
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 -
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. -
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 -
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… -
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 -
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 -
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 -
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” -
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 -
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 -
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 -
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) -
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!!!) -
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 -
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 -
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 -
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 (,) -
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 -
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 -
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 -
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 -
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 -
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 } -
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 -
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 -
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! -
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 -
Algorithms • As for the remaining three methods, we need
to design some algorithms to guide the coding for each method -
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 -
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) -
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 -
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 -
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) -
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 -
Memory Defragmenter • Special character escape sequences • Write to
a file • Spaghetti code vs. Bento code • Grocery list problem and solution -
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!