This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

Size: px
Start display at page:

Download "This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java."

Transcription

1 CS121: Computer Programming I A) Collections B) File I/O & Error Handling Dr Olly Gotel ogotel@pace.edu Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors This Week s Agenda (Part A) Card tricks & data types CORE CONCEPT - the array a very useful ingredient Multidimensional arrays There is something called an ArrayList that is actually more useful than an array & we ll get to that soon CS121/IS223 Week 8, Slide 1 CS121/IS223 Week 8, Slide 2 The Games People Play If I randomly deal 5 cards, how do I keep track of all the cards in this hand? 5 separate variables? Argh! Data Types & Structures Functions & methods provide a way to group program statements together Data types & structures provide a way to group variables & organise data benefits are organisation & speed Would I really use 52 variables to model a deck of cards???? i.e. types that hold multiple values CS121/IS223 Week 8, Slide 3 An important data type in most high-level programming languages is the array it groups data into lists You will learn how to create other data structures (e.g. stacks, queues, linked lists, graphs & trees) in later classes CS121/IS223 Week 8, Slide 4 The Array in Java Used for storing collections of data The Array in Java An array is a special kind of Java object It allows you to create a variable that contains a sequence of data items of ONE given type Each item in the array (element) has an index, so an array is a bit like an indexed list of variables Classic example: a deck of cards deck[52] deck[4][13] deck[52] - you could have 52 elements each representing one card deck[4][13] - you could have a 2-dimensional array where the first element represents the suit and the second the face value CS121/IS223 Week 8, Slide 5 CS121/IS223 Week 8, Slide 6 1

2 What Does an Array Look Like? [10] Indices Values held here [6] CS121/IS223 Week 8, Slide 7 [3] Simple Array Example If we want to write a program to compute the average mark for all students in this class, we could write the following Java code: int students = 10; double next = 0, sum = 0, average = 0; Scanner scan = new Scanner(System.in); System.out.println( Enter marks: ); for (int count = 0; count < students; count++){ next = scan.nextdouble(); sum = sum + next; average = sum / students; System.out.println( Average: + average); CS121/IS223 Week 8, Slide 8 Example in Action BUT, how do we work out & print all marks below the average? We lost track of all the grades entered! Amnesia? Creating & Accessing an Array Placeholder Java collections double[] marks = new double[10]; Identical to declaring 10 variables of type double: marks[0], marks[1], marks[2] marks[9] Array index starts with 0, NOT 1; Array index ends at array size 1 Assign values: marks[0] = 45, marks[1] = 88 Arrays allow us to save information that we can access later on - they provide an elegant way to declare a collection of related variables Do things: System.out.println(marks[1]); etc. CS121/IS223 Week 8, Slide 9 CS121/IS223 Week 8, Slide 10 What Does marks Look Like? Important Explanation Once declared, can t change size Indices Each slot holds its own unique double value e.g. marks[4] = 2.0; double[] marks = new double[10]; CS121/IS223 Week 8, Slide 11 temp[0] is 21.2 temp[1] is 32.0 temp[2] is 77.1 temp[3] is 2.8 temp[4] is 9.62 temp[5] is array slots! double[] temp = new double[6] NOT double[] temp = new double[5] CS121/IS223 Week 8, Slide 12 2

3 Example Continued (i) What Does This Populated Array Look Like? Indices Use Scanner for reading keyboard input here Creating the array for loops are often used to iterate through array items Use array items just like variables The array called marks Value of the indexed variable marks[8] The indexed variable marks[6] - it is the 7th slot CS121/IS223 Week 8, Slide 13 CS121/IS223 Week 8, Slide 14 Example Continued (ii) You WILL Forget this Use Scanner for reading keyboard input here Now simple to check each grade Remember indexing starts from 0, so the 1 st element is marks[0] & the last element is marks[array_length 1] Remember this when you get array out of bounds errors! CS121/IS223 Week 8, Slide 15 CS121/IS223 Week 8, Slide 16 General Way to Create an Array arraytype[] arrayname = new arraytype[arraylength]; arraytype can be any primitive type or class type - but let us stick with arrays of primitives for now because arrays of objects work differently!!! An array is an object you can ask it its length: arrayname.length marks.length has value 10 Small number of such array methods in Java see the API CS121/IS223 Week 8, Slide 17 Extending the Example Use Scanner for reading keyboard input here Dynamically creates the array size Dynamically deals with indices CS121/IS223 Week 8, Slide 18 3

4 Initialising Arrays Arrays can be initialised when declared: Initialiser list double[] marks = {98, 34, 66, 78, 45; The size of the array is set to the minimum necessary to hold the values (so 5 here, indexed 0 to 4) Default initialisation is to set every array element to 0: double[] marks = new double[5]; for (int i = 0; i < marks.length; i++) marks[i] = 0; Changing Array Elements You can access & change array elements like any other variable double[] marks = {98, 34, 66, 78, 45; marks[0] = 45 Changes the value of the first array slot to the value of 45, so this is what is now in the array: {45, 34, 66, 78, 45 CS121/IS223 Week 8, Slide 19 CS121/IS223 Week 8, Slide 20 Exercise double temp[] = {55.1, -4.3, 2.0, -33.9, 2.45, What is the size (length) of this array? 6 What value is at temp[3]? What value is at temp[6]? Out of bounds!!! Write an assignment to change the value of 2.45 to 8.1 temp[4]=8.1; TO DO: See if you can write a loop to find the array slot holding the value 2.45 and when you do, update the slot to hold 8.1 instead Out of Bounds Errors double[] marks = new double[5]; for (int i = 0; i <= marks.length; i++) marks[i] = 100; Here, when i = 5 we try to put the value 100 into marks[5] this location does not exist! Because we count from 0, mark s[4] is actually the last slot - so be careful!!! When we try to access a non-existent array element, we create an out of bounds error What can we do to correct this problem? Use < and not <= CS121/IS223 Week 8, Slide 21 CS121/IS223 Week 8, Slide 22 Exercise An Answer Write a Java program that creates an integer array of 10 elements, then places the numbers 1 to 10 in this array: use a for loop to initialise the array use another for loop to print the contents of the array on a single line Remember array indices start from 0, so you want to put the number 1 in array position 0 Call your file FirstArray.java CS121/IS223 Week 8, Slide 23 CS121/IS223 Week 8, Slide 24 4

5 Exercise An Answer Write a Java program that creates a character array to store the letters in your first name: make the size of the array the same size as the number of letters in your name initialise the array to contain these letters use a for loop to print out the letters, each on a separate line Remember characters use single quotes j Call your file SecondArray.java CS121/IS223 Week 8, Slide 25 CS121/IS223 Week 8, Slide 26 Exercise Write a Java program that creates a double array to store 15 numbers: write a for loop to ask the user to enter 15 numbers inside this for loop, place each of the entered numbers in the array use another for loop to print out the numbers An Answer Use Scanner for reading keyboard input here Call your file ThirdArray.java CS121/IS223 Week 8, Slide 27 CS121/IS223 Week 8, Slide 28 Multidimensional Arrays As You Would Guess? rows columns How do you think we represent this in a Java program? Apr May June July Aug Sept CS121/IS223 Week 8, Slide 29 double[][] table = new double[4][6]; This time, you need to use a nested for loop to initialise or print out the array values: for all the rows for all the columns dosomething(to element at index pinpointed by row & column); Initialiser list - values are loaded using nested arrays: {{first_row values, {second row values, etc e.g. {{2.1.2, 32.0, 77.1, 2.8, 9.62, 6.11, etc CS121/IS223 Week 8, Slide 30 5

6 Example A Java program that puts these values in a 2 -dimensional array, then prints them out CS121/IS223 Week 8, Slide 31 Example Code Each row separately double[][] table = {{21.2,32.0,77.1,2.8,9.62,6.11, {24.2,32.0,79.1,12.8,99.62,2.31, {31.2,32.0,87.1,86.3,7.62,99.11, {91.8,32.0,11.1,3.48,8.14,7.4; for (int row = 0; row < table.length; row++){ Think in the other dimension! for (int col = 0; col <table[row].length; col++){ System.out.println(table[row][col]); System.out.println(); See - these nested loops come in handy! CS121/IS223 Week 8, Slide 32 NOTE To check whether 2 arrays are equal (i.e. hold the same elements), you need to loop through the arrays checking for the equality of each element at the corresponding index position You can t say (array1 == array2)!? Your loops are critical for manipulating collections, that s why we practice them lots Exercise Write a Java program that keeps a record of how many hours you spent gaming each day over a period of 4 weeks: use a 2-dimensional array prompt the user to enter the hours played for each day in week 1, then in week 2, etc print out the following: Week 1, Day 1: xxx hours of gaming Week 1, Day 2: yyy hours of gaming Call your file GameArray.java Week 4, Day 7: zzz hours of gaming CS121/IS223 Week 8, Slide 33 CS121/IS223 Week 8, Slide 34 Something Similar Challenge Think about it! How about representing a tic-tac-toe board? Use Scanner for reading keyboard input here One dimensional array or two dimensional? How would you place characters & play a game? char[][] tic = new char[3][3] tic[2][2] = x How could you make the computer play to win? AI? TO DO: write a 2 player tic-tac-toe game for me!!! CS121/IS223 Week 8, Slide 35 CS121/IS223 Week 8, Slide 36 6

7 Hint: Create and Initialise (step 1) char[][] ttt = new char[3][3]; for (int i = 0; i< ttt.length; i++){ for (int j=0; j< ttt[i].length; j++){ ttt[i][j]= ' '; Hint: Hard-wire Populate (step 2) ttt[0][0] = 'x'; ttt[0][1] = 'o'; ttt[0][2] = 'o'; ttt[1][0] = 'x'; ttt[1][2] = 'x'; ttt[2][0] = 'o'; ttt[2][1] = 'o'; ttt[2][2] = 'x'; CS121/IS223 Week 8, Slide 37 CS121/IS223 Week 8, Slide 38 Hint: Print Board (step 3) for (int i = 0; i< ttt.length; i++){ for (int j=0; j< ttt[i].length; j++){ System.out.print(ttt[i][j]); System.out.println(); Another Dimension? 3+ di arrays in Java not recommended NOW change the hardwired bit to accept input and check whether X or O is already in a slot if not, put in in! How would you check for a winner? char[][][] cube = new char[4][5][3] CS121/IS223 Week 8, Slide 39 CS121/IS223 Week 8, Slide 40 Key Points Arrays are a data structure for dealing with a collection of variables of the same type Array indices start from ZERO in Java - never from 1 The last index in an array is always one less than the array length in Java (so, n 1) This Week s Agenda (Part B) Simple error handling & exceptions File input & output: opening, closing, reading & writing Out of bounds errors are a common mistake when using arrays (i.e. trying to access an array element that does not exist) Using arrays, you need to perfect your for loops! CS121/IS223 Week 8, Slide 41 CS121/IS223 Week 8, Slide 42 7

8 Error Handling Errors 3 main types of error NO! Syntax errors: violation of language s grammatical rules prevents program from running Logic (semantic) errors: flawed algorithms or thinking program runs but doesn t produce the results you expect Runtime errors: error that occurs when a programming is running, due to things like nonsense input program often aborts (crashes) CS121/IS223 Week 8, Slide 43 CS121/IS223 Week 8, Slide 44 Error Detection Most IDEs help you with syntax errors Java raises an exception when it detects a runtime error Logic (semantic) errors you are on your own: so important to get your algorithms right! Exceptions Errors at runtime cause exceptions: division by zero trying to extract a list element that doesn t exist trying to open a file that doesn t exist entering a string when a number is expected It is bad practice to let runtime errors crash your program It is good practice to check for such errors (catch them) & handle them You could write a jumble of code to check for all sorts of conditions, but there is a neater way to do this You have to think about what could go wrong in your program & what to do about it! CS121/IS223 Week 8, Slide 45 CS121/IS223 Week 8, Slide 46 This is a BIG topic & will be looked at more later Error Handling in Java In Java An exception is signalled by a program or runtime environment when it encounters an unusual or incorrect situation this is called throwing an exception Exceptions can be caught & handled by programs this is called handling an exception Exception handling helps you create robust programs & you should use it for potential risky code, where simple conditional checks are not sufficient In Java, there are some built-in exceptions you can use, but you are more likely to need to write your own you do this by writing a class System.exit(0) ends a program CS121/IS223 Week 8, Slide 47 In Java, we use: Try block try { if (denominator==0) throw new DivideByZeroException(); catch(dividebyzeroexception e){ System.out.println( Can t divide by zero ); Catch block An exception is an object of type Exception - You can define your own class of exception, throw them in your programs & catch them! CS121/IS223 Week 8, Slide 48 8

9 Considerations & Options Options for dealing with issues at runtime: Ignore (duh! But sometimes what can you do?) Handle when encountered (catch it) Handle later (propagate it) An exception is an object of type Exception, you can define your own class of exception using inheritance, throw instances in your programs & catch them - exceptions are polymorphic [LATER!] You may want to deal with multiple types of exception if you want to distinguish many types of problem (i.e. diagnostics) CS121/IS223 Week 8, Slide 49 try catch finally Potentially dodgy code can create & then throw try { different exception objects here if needed whatever; Exception handlers as many as you need for type -specific recovery execution passes to finally clause as soon as one is matched & executed catch(dividebyzeroexception e){ System.out.println( Can t div by 0 ); catch(numberformatexception e){ System.out.println( Not numeric ); finally{ Definitely execute if present Maybe execute (i.e. if type matches) Optional. Executed no matter how the try block is executed System.out.println( I m done ); Can guarantee something happens CS121/IS223 Week 8, Slide 50 Explanation Example in a minute Input & Output If an exception occurs at any point when executing the try block, control is passed to the appropriate catch handler (i.e. the clause whose exception class matches that of the exception thrown) Then, control passes to statement following the entire try..catch block A finally clause just ensures that something always happens irrespective of what went on before (like when you leave the house you always want to make sure you lock the door) Input so far via keyboard Output so far via monitor (print) It is often useful to access files from within a program to read, write & manipulate stored data File I/O We will only look at the basics CS121/IS223 Week 8, Slide 51 CS121/IS223 Week 8, Slide 52 Why Bother With Files? You can deal with larger input & output You can do all sorts of manipulation with the contents of files (they are just strings & lists, so you can traverse, reverse, etc): counting words counting lines This is just the tip of the iceberg for now! changing words changing case finding words adding markup making permanent records CS121/IS223 Week 8, Slide 53 File Input/Output File I/O, as well as simple keyboard & screen I/O, is handled by streams in Java A stream is an object that either: delivers data to a destination (e.g. file or screen) takes data from a source (e.g. file or keyboard) & delivers it to a program System.out object is an output stream for screen output System.in implements the standard input stream that reads characters from the keyboard. CS121/IS223 Week 8, Slide 54 9

10 What is a Stream? A flow of data (characters, numbers, etc) Input stream data flows into a program Output stream data flows out of a program Streams are implemented as objects of special stream classes in Java (don t worry about the details for now) We will look only at text files for now CS121/IS223 Week 8, Slide 55 You must import this for dealing with file I/O at the start of the class Writing Text to a File (File Output) import java.io.*; Variable of class type PrintWriter PrintWriter outputstream = null; Generally placed inside a try-catch outputstream = new PrintWriter(new FileOutputStream( out.txt )); Preferred stream class for writing to a text file in Java This connects a stream called outputstream to a file called out.txt It creates the file out.txt if it doesn t exist, or opens & overwrites it if it does exist Once created, you can write to the file using familiar statements - outputstream.println( whatever ); & close it using outputstream.close(); CS121/IS223 Week 8, Slide 56 *NOTE import java.util.scanner and make a Scanner object to read stuff in *TRY THIS OUT* Reading Text from a File (File Input) import java.io.*; Variable of type BufferedReader BufferedReader inputstream = new BufferedReader(new FileReader( data.txt )); From [Savitch 2004] Use Scanner methods here See listing 8.9 in ed 3 of text those of you without ed 3 can download code from the text website CS121/IS223 Week 8, Slide 57 Generally placed inside a try-catch The class BufferedReader is the preferred stream class for reading from a text file; class FileReader helps us open a file This connects a text file to a stream of the class BufferedReader to enable your program to read from a file Once open, you can read from the file using familiar statements line = inputstream.readline(); & close it using inputstream.close(); CS121/IS223 Week 8, Slide 58 Sets up the input stream, reads & processes it a line at a time data.txt 1 2 buckle my shoe. 3 4 shut the door. You Read Strings When you read in from data files, you always read in a String String s = inputstream.readline(); *NOTE *TRY THIS OUT* See listings 8.7 & 8.8 (ed 3) in text - it tokenizes the From [Savitch 2004] input & uses it to create objects those of you without CS121/IS223 ed 3 can download code from the text website Week 8, Slide 59 To read in a string & convert to an integer String s = inputstream.readline(); num = Integer.parseInt(s); Wrapper types To read in a string & convert to a double String s = inputstream.readline(); num = Double.parseDouble(s); CS121/IS223 Week 8, Slide 60 10

11 StringTokenizer Using a StringTokenizer [Lewis & Loftus 2004] Java class used to extract & process data in a string import java.util.stringtokenizer to use it Tokens the name for the individual elements that comprise a string Tokenizing the name we give to the process of extracting elements from a string Delimiters the characters that separate tokens Possible token I want my coffee, now! Possible delimiters you choose them CS121/IS223 Week 8, Slide 61 import java.util.scanner; import java.util.stringtokenizer; public class CountWords{ public static void main (String[] args){ int wordcount = 0, charactercount = 0; String line, word; Scanner scan = new Scanner(System.in); StringTokenizer tokenizer; So you can use the class & its methods Declares a variable of StringTokenizer type System.out.println ("Please enter text (type DONE to quit):"); Makes a StringTokenizer object line = scan.nextline(); while (!line.equals("done")){ tokenizer = new StringTokenizer (line); Checks if tokens in string while (tokenizer.hasmoretokens()){ word = tokenizer.nexttoken(); Gets next token from a string wordcount++; charactercount += word.length(); line = scan.nextline(); System.out.println ("Number of words: " + wordcount); System.out.println ("Number of characters: " + charactercount); Reads several lines of text, counting the number of words & the number of non-space characters CS121/IS223 Week 8, Slide 62 Other Delimiters When you create a StringTokenizer object, state what delimiters you want it to use final String DELIMS = "`~!(){[]\"':;,.?-\n\t "; StringTokenizer tokenizer; String line; tokenizer = new StringTokenizer (line, DELIMS); String to tokenize Final modifier declares a constant String that provides a set of delimiters CS121/IS223 Week 8, Slide 63 Key Points (Part B) Exceptions & file handling are big topics in Java! There are a number of built-in exceptions you can use, but you will need to learn to write your own & understand how they work (requires OO thinking) File I/O is very sophisticated! For now, & until you encounter file I/O further, you need to take a few things on faith & use the standard code - as with public static void main (String[] args) - please explore the API for more info if interested CS121/IS223 Week 8, Slide 64 Before Next Time Reading: if 3 rd edition - read Chapter 6.0 of the Java book; lightly skim sections 8.0 to 8.3 if 4 th - 6 th edition read Chapter of the Java book; lightly skim sections 10.1 to 10.3 Try to keep up with your exercises you should be on exercise sheet 2 and start working on part B Coming Up Next Time An object-oriented primer - thinking with objects! Classes, objects and methods - looking at program structure and control flow Don t forget that the exercise sheets and readings are designed for YOUR practice! CS121/IS223 Week 8, Slide 65 CS121/IS223 Week 8, Slide 66 11

CS121: Computer Programming I

CS121: Computer Programming I CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours

More information

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements

This Week s Agenda (Part A) CS121: Computer Programming I. Changing Between Loops. Things to do in-between Classes. Answer. Combining Statements CS121: Computer Programming I A) Practice with Java Control Structures B) Methods Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours

More information

IT101. File Input and Output

IT101. File Input and Output IT101 File Input and Output IO Streams A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents

More information

HST 952. Computing for Biomedical Scientists Lecture 8

HST 952. Computing for Biomedical Scientists Lecture 8 Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java

More information

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file

More information

Streams and File I/O

Streams and File I/O Chapter 9 Streams and File I/O Overview of Streams and File I/O Text File I/O Binary File I/O File Objects and File Names Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Exceptions: The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception

More information

CSPP : Introduction to Object-Oriented Programming

CSPP : Introduction to Object-Oriented Programming CSPP 511-01: Introduction to Object-Oriented Programming Harri Hakula Ryerson 256, tel. 773-702-8584 hhakula@cs.uchicago.edu August 7, 2000 CSPP 511-01: Lecture 15, August 7, 2000 1 Exceptions Files: Text

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

File I/O and Exceptions

File I/O and Exceptions File I/O and Exceptions CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

Simple Java Input/Output

Simple Java Input/Output Simple Java Input/Output Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it

More information

Java Input/Output. 11 April 2013 OSU CSE 1

Java Input/Output. 11 April 2013 OSU CSE 1 Java Input/Output 11 April 2013 OSU CSE 1 Overview The Java I/O (Input/Output) package java.io contains a group of interfaces and classes similar to the OSU CSE components SimpleReader and SimpleWriter

More information

Input from Files. Buffered Reader

Input from Files. Buffered Reader Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

More information

Lesson 3: Accepting User Input and Using Different Methods for Output

Lesson 3: Accepting User Input and Using Different Methods for Output Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program

More information

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board Ananda Gunawardena Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO Lab 1 Objectives Learn how to structure TicTacToeprogram as

More information

When we reach the line "z = x / y" the program crashes with the message:

When we reach the line z = x / y the program crashes with the message: CSCE A201 Introduction to Exceptions and File I/O An exception is an abnormal condition that occurs during the execution of a program. For example, divisions by zero, accessing an invalid array index,

More information

Input/Output (I/0) What is File I/O? Writing to a File. Writing to Standard Output. CS111 Computer Programming

Input/Output (I/0) What is File I/O? Writing to a File. Writing to Standard Output. CS111 Computer Programming What is File I/O? Input/Output (I/0) Thu. Apr. 12, 2012 Computer Programming A file is an abstraction for storing information (text, images, music, etc.) on a computer. Today we will explore how to read

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015 COMP-202: Foundations of Programming Lecture 22: File I/O Jackie Cheung, Winter 2015 Announcements Assignment 5 due Tue Mar 31 at 11:59pm Quiz 6 due Tue Apr 7 at 11:59pm 2 Review 1. What is a graph? How

More information

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

AP Computer Science Lists The Array type

AP Computer Science Lists The Array type AP Computer Science Lists There are two types of Lists in Java that are commonly used: Arrays and ArrayLists. Both types of list structures allow a user to store ordered collections of data, but there

More information

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 Contents 1 Exceptions and How They Work 1 1.1 Update to the Banking Example.............................

More information

CS121/IS223. Collections Revisited. Dr Olly Gotel

CS121/IS223. Collections Revisited. Dr Olly Gotel CS121/IS223 Collections Revisited Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

REMINDER CS121/IS223. Agenda. A Recap on Arrays. Array of Cars for the Car Race? Arrays of Objects (i)

REMINDER CS121/IS223. Agenda. A Recap on Arrays. Array of Cars for the Car Race? Arrays of Objects (i) Collections Revisited Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors REMINDER There is no class

More information

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous CS256 Computer Science I Kevin Sahr, PhD Lecture 25: Miscellaneous 1 main Method Arguments recall the method header of the main method note the argument list public static void main (String [] args) we

More information

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam! Last Time Announcements (Midterm Exam!) Assn 2 due tonight. Before that methods. Spring 2006 CISC101 - Prof. McLeod 1 Spring 2006 CISC101 - Prof. McLeod 2 Today Look at midterm solution. Review method

More information

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs Ananda Gunawardena Java APIs Think Java API (Application Programming Interface) as a super dictionary of the Java language. It has a list of all Java packages, classes, and interfaces; along with all of

More information

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab. Lab 14 Name: Checked: Objectives: Practice handling exceptions and writing text files. Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of

More information

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Arrays CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying Java Software Solutions

More information

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

File I/O Introduction to File I/O Text Files The File Class Binary Files 614 10.1 Introduction to File I/O 574 Streams 575 Text Files and Binary Files 575 10.2 Text Files 576 Writing to a Text File 576 Appending to a Text File 583 Reading from a Text File 586 Reading a Text File

More information

COMP 202. Programming With Arrays

COMP 202. Programming With Arrays COMP 202 Programming With Arrays CONTENTS: Arrays, 2D Arrays, Multidimensional Arrays The Array List Variable Length parameter lists The Foreach Statement Thinking Like A Programmer: Designing for arrays

More information

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice CONTENTS: Arrays Strings COMP-202 Unit 5: Loops in Practice Computing the mean of several numbers Suppose we want to write a program which asks the user to enter several numbers and then computes the average

More information

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #07: September 21, 2015 1/30 We explained last time that an array is an ordered list of values. Each value is stored at a specific, numbered position in

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

1.00 Lecture 30. Sending information to a Java program

1.00 Lecture 30. Sending information to a Java program 1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes

More information

Exercise 4: Loops, Arrays and Files

Exercise 4: Loops, Arrays and Files Exercise 4: Loops, Arrays and Files worth 24% of the final mark November 4, 2004 Instructions Submit your programs in a floppy disk. Deliver the disk to Michele Zito at the 12noon lecture on Tuesday November

More information

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO Ananda Gunawardena Objects and Methods working together to solve a problem Object Oriented Programming Paradigm

More information

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:

More information

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING INPUT AND OUTPUT Input devices Keyboard Mouse Hard drive Network Digital camera Microphone Output devices.

More information

CSCI 1103: File I/O, Scanner, PrintWriter

CSCI 1103: File I/O, Scanner, PrintWriter CSCI 1103: File I/O, Scanner, PrintWriter Chris Kauffman Last Updated: Mon Dec 4 10:03:11 CST 2017 1 Logistics Reading from Eck Ch 2.1 on Input, File I/O Ch 11.1-2 on File I/O Goals Scanner for input Input

More information

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software. CISC-124 20180129 20180130 20180201 This week we continued to look at some aspects of Java and how they relate to building reliable software. Multi-Dimensional Arrays Like most languages, Java permits

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

4. Java language basics: Function. Minhaeng Lee

4. Java language basics: Function. Minhaeng Lee 4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only

More information

Java I/O and Control Structures

Java I/O and Control Structures Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying

More information

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved. Chapter 10 File I/O Copyright 2016 Pearson Inc. All rights reserved. Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program,

More information

Exceptions. What exceptional things might our programs run in to?

Exceptions. What exceptional things might our programs run in to? Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don

More information

Exceptions in Java

Exceptions in Java Exceptions in Java 3-10-2005 Opening Discussion Do you have any questions about the quiz? What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment?

More information

Introduction Unit 4: Input, output and exceptions

Introduction Unit 4: Input, output and exceptions Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Lab 5: Java IO 12:00 PM, Feb 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering

More information

Arrays. Chapter 7 Part 3 Multi-Dimensional Arrays

Arrays. Chapter 7 Part 3 Multi-Dimensional Arrays Arrays Chapter 7 Part 3 Multi-Dimensional Arrays Chapter 7: Arrays Slide # 1 Agenda Array Dimensions Multi-dimensional arrays Basics Printing elements Chapter 7: Arrays Slide # 2 First Some Video Tutorials

More information

2: Basics of Java Programming

2: Basics of Java Programming 2: Basics of Java Programming CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

CSCI 261 Computer Science II

CSCI 261 Computer Science II CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -

More information

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation. Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide CS1092: Tutorial Sheet: No 3 Exceptions and Files Tutor s Guide Preliminary This tutorial sheet requires that you ve read Chapter 15 on Exceptions (CS1081 lectured material), and followed the recent CS1092

More information

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading. Last Time Reviewed method overloading. A few useful Java classes: Other handy System class methods Wrapper classes String class StringTokenizer class Assn 3 posted. Announcements Final on June 14 or 15?

More information

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7) Array Basics: Outline Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and Constants

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu (Using the Scanner and String Classes) Anatomy of a Java Program Readings This Week s Reading: Ch 3.1-3.8 (Major conceptual jump

More information

Full file at

Full file at Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as

More information

Java I/O and Control Structures Algorithms in everyday life

Java I/O and Control Structures Algorithms in everyday life Introduction Java I/O and Control Structures Algorithms in everyday life CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Source: http://xkcd.com/627/

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CS 251 Intermediate Programming Java I/O Streams

CS 251 Intermediate Programming Java I/O Streams CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package

More information

PIC 20A Streams and I/O

PIC 20A Streams and I/O PIC 20A Streams and I/O Ernest Ryu UCLA Mathematics Last edited: December 7, 2017 Why streams? Often, you want to do I/O without paying attention to where you are reading from or writing to. You can read

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

CSCI 1103: File I/O, Scanner, PrintWriter

CSCI 1103: File I/O, Scanner, PrintWriter CSCI 1103: File I/O, Scanner, PrintWriter Chris Kauffman Last Updated: Wed Nov 29 13:22:24 CST 2017 1 Logistics Reading from Eck Ch 2.1 on Input, File I/O Ch 11.1-2 on File I/O Goals Scanner for input

More information

File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)

File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10) File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". Input is received from the keyboard, mouse, files.

More information

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166 Lecture 22 Java Input/Output (I/O) Streams Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics I/O Streams Writing to a Stream Byte Streams Character Streams Line-Oriented I/O Buffered I/O

More information

Advanced Java Concept Unit 1. Mostly Review

Advanced Java Concept Unit 1. Mostly Review Advanced Java Concept Unit 1. Mostly Review Program 1. Create a class that has only a main method. In the main method create an ArrayList of Integers (remember the import statement). Add 10 random integers

More information

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website: Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

Two Dimensional Arrays

Two Dimensional Arrays + Two Dimensional Arrays + Two Dimensional Arrays So far we have studied how to store linear collections of data using a single dimensional array. However, the data associated with certain systems (a digital

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output.

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output. Program Structure Language Basics Selection/Iteration Statements Useful Java Classes Text/File Input and Output Java Exceptions Program Structure 1 Packages Provide a mechanism for grouping related classes

More information

Classes Basic Overview

Classes Basic Overview Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container

More information

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score CSC 1051 Algorithms and Data Structures I Final Examination May 2, 2016 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces provided.

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

Lesson 10: Quiz #1 and Getting User Input (W03D2)

Lesson 10: Quiz #1 and Getting User Input (W03D2) Lesson 10: Quiz #1 and Getting User Input (W03D2) Balboa High School Michael Ferraro September 1, 2015 1 / 13 Do Now: Prep GitHub Repo for PS #1 You ll need to submit the 5.2 solution on the paper form

More information

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: CSC 1051 Algorithms and Data Structures I Final Examination May 2, 2016 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces provided.

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics Inf1-OP Inf1-OP Exam Review Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 20, 2017 Overview Overview of examinable material: Lectures Week 1

More information

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O) 116 7. Java Input/Output User Input/Console Output, File Input and Output (I/O) 117 User Input (half the truth) e.g. reading a number: int i = In.readInt(); Our class In provides various such methods.

More information

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1 COMP 202 File Access CONTENTS: I/O streams Reading and writing text files COMP 202 - File Access 1 I/O Streams A stream is a sequence of bytes that flow from a source to a destination In a program, we

More information

I. Variables and Data Type week 3

I. Variables and Data Type week 3 I. Variables and Data Type week 3 variable: a named memory (i.e. RAM, which is volatile) location used to store/hold data, which can be changed during program execution in algebra: 3x + 5 = 20, x = 5,

More information

CS159 Midterm #1 Review

CS159 Midterm #1 Review Name: CS159 Midterm #1 Review 1. Choose the best answer for each of the following multiple choice questions. (a) What is the effect of declaring a class member to be static? It means that the member cannot

More information

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015 Announcements Assignment 4 is posted and Due on 29 th of June at 11:30 pm. Course Evaluations due

More information

Project #1 Computer Science 2334 Fall 2008

Project #1 Computer Science 2334 Fall 2008 Project #1 Computer Science 2334 Fall 2008 User Request: Create a Word Verification System. Milestones: 1. Use program arguments to specify a file name. 10 points 2. Use simple File I/O to read a file.

More information