CS 302: Introduction to Programming in Java. Lectures 17&18. It s insanely hot. People desperately need some snowflakes

Similar documents
11/1/2011. Chapter Goals

Input-Output and Exception Handling

First Java Program - Output to the Screen

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

Reading Input from Text File

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

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

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

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

Unit 10: exception handling and file I/O

Example Program. public class ComputeArea {

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

File I/O Array Basics For-each loop

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

Computer Science is...

Reading Text Files. 1 Reading from text files: Scanner

A token is a sequence of characters not including any whitespace.

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

CP122 CS I. Chapter 11: File I/O and Exceptions

Dining philosophers (cont)

CIS 110: Introduction to Computer Programming

Object-Oriented Programming in Java

Excep&ons and file I/O

Java Console Input/Output The Basics

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Midterms Save the Dates!

Files & Exception Handling. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

FILE I/O. CS302 Introduction to Programming University of Wisconsin Madison Lecture 27. By Matthew Bernstein

Program 12 - Spring 2018

Chapter 4: Loops and Files

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Chapter 4: Loops and Files

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

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

Lecture Set 2: Starting Java

Java Console Input/Output The Basics. CGS 3416 Spring 2018

Lecture Set 2: Starting Java

BBM 102 Introduction to Programming II Spring Exceptions

CP122 CS I. Chapter 11: File I/O and Exceptions

Building Java Programs

Files. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

CS 177 Recitation. Week 1 Intro to Java

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

CSCI 1103: File I/O, Scanner, PrintWriter

COMP-202 Unit 9: Exceptions

Simple Java Input/Output

Exceptions. When do we need exception mechanism? When and why use exceptions? The purpose of exceptions

Text User Interfaces. Keyboard IO plus

CS 455 Midterm Exam 2 Fall 2015 [Bono] Nov. 10, 2015

CS 302: Introduction to Programming

4. Java Project Design, Input Methods

Java Input/Output. 11 April 2013 OSU CSE 1

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Fall 2017 CISC124 10/1/2017

CMSC 202. Exceptions

Introduction Unit 4: Input, output and exceptions

CP122 CS I. Chapter 7: File I/O and Exceptions

EXCEPTIONS. Fundamentals of Computer Science I

Files. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:

COMP 202 Java in one week

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

CSCI 1103: File I/O, Scanner, PrintWriter

CSCI 261 Computer Science II

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

Java Errors and Exceptions. Because Murphy s Law never fails

Building Java Programs

Input. Scanner keyboard = new Scanner(System.in); String name;

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

BBM 102 Introduction to Programming II Spring 2017

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

ASSIGNMENT 5 Objects, Files, and More Garage Management

Java Concepts and Style;

ASSIGNMENT 5 Objects, Files, and a Music Player

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Fundamentos de programação

Exceptions Handeling

Java Coding 3. Over & over again!

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1

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

CS 231 Data Structures and Algorithms Fall 2018

Lab 2: File Input and Output

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

CS 302: Introduction to Programming in Java. Lecture 12

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Code Ninjas: Introduction to Computer Science. Macomb Science Olympiad Presented by Swati Dharia

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Computational Expression

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Transcription:

CS 302: Introduction to Programming in Java Lectures 17&18 It s insanely hot. People desperately need some snowflakes

Static variables Again (class variables) Variables unique to the class (all objects of this type will have access to these variables and there is only 1 of each variable) Different from regular instance variables All ojects of this type get their own copies of the regular instance variables Often used for identification of objects

ArrayLists and Objects ArrayLists can be a list of objects ArrayList<BankAccount> accounts = new ArrayList<BankAccount>(); Now can call any of the ArrayList methods (.add(),.get(), etc.) on accounts Each index of accounts will be a BankAccount object accounts.get(0).deposit(100);

Grab-bag chapter 3 Foci: Chapter 8 Reading/Writing Files Parsing text files Navigating directories Command Line arguments Exception Handling Throwing exceptions Catching exceptions Don't mistake this chapter for being unimportant (material will show up on the final)

Reading / Writing Text Files Use Scanner Scanner takes input from whatever you pass it in its constructor Scanner stdin = new Scanner(System.in); System.in is default input (i.e. keyboard) from the operating system File inputfile = new File("input.txt"); Scanner filereader = new Scanner(inputFile) Can now use familiar scanner methods to parse inputfile (next, nextline, nextint, nextdouble)

The File Object Represents a path (not neccessarily a file) To instantiate: File whatever = new File("path"); "Path" must be absolute path ("C:\\folder1\\folder2...\\file.extension"); Exception: the file you want to open is in your Java project In this case just give the file name Several useful methods (creating files, deleting files, etc.) - take a look at the Java API Can represent a path where no file is yet File filetocreate = new File("newFile.txt"); filetocreate.createnewfile(); Can represent a directory (folder)

Using Files and Scanner - Input What does this loop do? File file = new File("input.txt"); Scanner filereader = new Scanner(file); while (in.hasnextline()) { String line = in.nextline(); //Do something with line }

File Output: PrintWriter To output data to a file use PrintWriter object Can construct in 2 ways: PrintWriter out = new PrintWriter("filepath"); PrintWriter out = new PrintWriter(File file); Caution: if file already exists, PrintWriter will clear it completely before printing anything to it If file didn't exist PrintWriter will create it

PrintWriter Example PrintWriter out = new PrintWriter("out.txt"); out.println("hello fileoutput world!"); out.print("i can use any of the familiar System.out" + " calls and conventions"); out.println("\nincluding the escape sequence"); out.close();

Notes on Text input/output ALWAYS close your Scanner and PrintWriter objects before exiting your program scannername.close(); printwritername.close(); If you don't, you might lose some data FileNotFoundException Can be thrown for a variety of reasons such as: the file you used to construct your Scanner didn't exist the file you gave your PrintWriter had an illegal name you didn't have write permissions to create file To fix: add "throws FileNotFoundException" to the method header in which the file input/output is done

Processing Text Input Read a file word by word: while(in.hasnext()) { String word = in.next(); } Read a file line by line: while(in.hasnext()) { String line = in.nextline(); }

Example Input file: Mary had a little lamb. China 1440044605 India 1147995898 United States 31382464 How can parsing be done using word by word or line by line?

Reading numbers Use in.hasnextint(), in.nextint(), in.hasnextdouble(), in.nextdouble() methods: if (in.hasnextdouble()) { } double val = in.nextdouble(); NOTE: these methods do NOT consume anything that follows a number (whitespace or newline)

Using Numbers and Words Code: String country = in.nextline(); int population = in.nextint(); String nextcountry = in.nextline(); What is the value of nextcountry? Input file: China 1330044605 India 1147995898 United States 303824646

Reading Characters Can read a single character at a time: Scanner in = new Scaner("whatever.txt"); in.usedelimiter(""); while(in.hasnext()) { char ch = in.next().charat(0); //do something with ch }

Practice 1 You have a short poem you made long time ago about Lake Mendota. One day on a whim, you wanna add line numbers for each line in the poem. Input file: dusk embraces Lake Mendota Author: Yinggang Huang When the golden sun was reflected in the water, the lake was ignited with sparks which is sooo eye enchanting. Hordes of ducks were sporting on the lake. A breeze swept across and then this scene got more dynamic. Waves and bubbles caused by sailboats danced together forming a visual rhythm. This state of harmony was just irresistible; it s like all these come back to me again soo naturally, it s really yesterday once more. Write a file named The Lake of Dreams.txt with line numbers added into the same folder as the original file.

Review What 2 objects are used for reading from text files What object is used to write to text files When giving absolute paths, what do you have to be careful of? If you don't give an absolute path, where does Java search for the file? What must you ALWAYS do when you are done reading / writing to/from files? What excpetion can be thrown when dealing with File IO

Command Line Arguments public static void main(string[] args) Before IDE's developers used simple text editors to write code (think notepad) They then used a shell (think cmd from Windows or Terminal from Mac OS) to compile and run their code (2 steps) You can still do this if you like: Compile: javac whatever.java Will produce a compiled file called "whatever.class" Run: java whatever Only works if there is already a "whatever.class"

Command Line Arguments Can pass arguments into the main method: java whatever -v input.txt Here 2 arguments were passed: "-v" and "input.txt" Arguments go to the String[] args in the main method String args now contains: ["-v", "input.txt"] Can do anything with the args array that you can do with normal arrays Example: check if any arguments were passed in: if (args.length!= 0)

Command Line Arguments - Eclipse Can pass in Command Line Arguments even if you aren't running from a shell In Eclipse: Run -> Run... Select "Arguments" tab Enter arguments seperated by spaces

Intro to Exceptions Exceptions = special but common error conditions that arise during runtime Two aspects: Detecting and Handling So far, our handling has simply been to quit the program, however we can do much more Ex. if we get a FileNotFoundException, why not prompt the user to enter a different file Detecting and Handling excpetions MUST be done seperately Ex. Scanner objects can detect FileNotFoundExceptions but cannot deal with them, they simply report it up the hierarchy

Throwing Exceptions If you only want to detect exceptions, your job is easy just "throw" a new exception object The only tricky part is figuring out which type of exception to throw Can create your own excpetions, but Java has many built in See textbook for common exceptions to throw If an exception is thrown, it immediately exits the method (like a return statement)

Throwing Exceptions Example What if we tried to delete a contact from our phonebook that wasn't in the phonebook? A "NoSuchElementException" lets use it if (!contactslist.contains(contacttodelete)) { } throw new NoSuchElementException("Contact " + contacttodelete.getname() " + wasn't in the phonebook");

Catching Exceptions All exceptions should be handled somewhere If an exception is not caught, your program will exit and you will get an error message To handle exceptions: use try/catch Try surrounds code that might throw an exception Catch deals with any exceptions should they arise

Try/Catch Example Contact acontact = new Contact("Billy", "Bob", 1234567, "nowhere"); try { } phonebook.remove(acontact); catch(nosuchelementexception e) { } System.out.println("Billy Bob wasn't in the phonebook");