CS-0401 INTERMEDIATE PROGRAMMING USING JAVA

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 4: Loops and Files
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
Chapter 5: Loops and Files.
1 CSE 142 Lecture Notes File input using Scanner Suggested reading: , Suggested self-checks: Section 6.7 # 1-11, These lecture.
1 Fall 2007ACS-1903 for Loop Writing to a file String conversions Random class.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
11 Chapter 4 LOOPS AND FILES CONT’D. 22 SENTINEL-CONTROLLED LOOPS Suppose we did not know the number of grades that were to be entered. Maybe, a single.
CS0007: Introduction to Computer Programming File IO and Recursion.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2014.
Chapter The Increment and Decrement Operators There are numerous times where a variable must simply be incremented or decremented. number = number.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Input and Output Using Text Files and Exception Handling.
Lecture 3 Looping and FIiling. 5-2 Topics – The Increment and Decrement Operators – The while Loop – Using the while Loop for Input Validation – The do.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Loops and Files Starting Out with Java From Control Structures.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Introduction to Computing Concepts Note Set 12. Writing a Program from Scratch public class SampleProgram1 { public static void main (String [] args)
Loops and Files. 5.1 The Increment and Decrement Operators.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
Starting Out With Java 5 Control Structures to Objects By Tony Gaddis Copyright © 2005, Pearson Addison-Wesley. All rights reserved. Chapter 4 Slide #1.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
1 Fall 2009ACS-1903 Writing Data To a File When writing to a file we need objects from the following classes are used to write data to files: FileWriter.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Chapter 4 Loops and Files. 2 Contents 1. The Increment and Decrement Operators 2. The while Loop 3. Using the while Loop for Input Validation 4. The do-while.
File - CIS 1068 Program Design and Abstraction
File I/O CLI: File Input CLI: File Output GUI: File Chooser
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
Reading from a file A file is typically stored on your computers hard drive. In the simplest case, lets just assume it is text. For a program to use.
INTERMEDIATE PROGRAMMING USING JAVA
Introduction to Exceptions in Java
Building Java Programs
File Input and Output TOPICS File Input Exception Handling File Output.
Chapter 5: Control Structures II
Lecture 4- Loops and Files
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
I/O Basics.
File Input and Output TOPICS File Input Exception Handling File Output.
Chapter 4: Loops and Files
Chapter 4: Loops and Files by Tony Gaddis and Godfrey Muganda
Topics Introduction to File Input and Output
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
CSS 161: Fundamentals of Computing
CMSC 202 Exceptions 2nd Lecture.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Dr. Sampath Jayarathna Cal Poly Pomona
CMSC 202 Exceptions 2nd Lecture.
Repetition Statements
Ch.4 – 5 Topics The auto Increment and Decrement Operators
Topics Introduction to File Input and Output
Loops CGS3416 Spring 2019 Lecture 7.
CMSC 202 Exceptions 2nd Lecture.
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, then the stream.
Presentation transcript:

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Spring 2018

Chapter 4 Loops and Files

Chapter 4 Presentation Outline First Part: Loops The increment and decrement operators The while Loop The do-while Loop The for loop Nested loops The break and continue statements Second Part: File Input and Output (if time allows) Introduction to File Input and Output Java Exceptions

First Part: Loop Structures

The While Loop

The While Loop https://www.youtube.com/watch?v=mRD5JCcjHrw&list=PL8071DACE30D40170 2012 Presidential Towers Stair Climb - Reference Video

The While Loop While Loop Syntax: Example: while(boolean condition is true) { execute commands inside } Example: int currentFloor = 10; int topFloor = 50; while(currentFloor < topFloor) { System.out.println(“Almost there! Floor: “ + currentFloor); currentFloor = currentFloor + 1; System.out.println(“Finally here! Top floor!”);

The While Loop The while loop is normally used when we do not know a priori when to stop We need to check the status of a given condition If the condition is true, execute the while loop body contents If the condition is false, terminate the WHILE loop The first check is performed BEFORE executing lines inside the loop.

Pay attention to infinite loops While Loop Pay attention to infinite loops int number = 0; while (number <=5) { System.out.println(“Hello”); number = number + 1; } What is wrong here ?

The “Guess the number” game

“Guess the number” game rules We will make the program to randomly generates a number from 0 to 100 (with the Java API Random Class) Then the program will keep asking the user to guess what the secret number is (with the Scanner/keyboard input) If the user guess a lower number, the program gives a message to try a higher number, otherwise a lower number When the user guess the right number, the program prints a message congratulating the user, shows how many guesses he/she took, and exits

The Do-While Loop

The Do-While Loop Syntax: statement(s); } while (condition); See TestAverage1.java

Increment and Decrement Operators

Increment Operator The following lines are equivalent! numberOfGuesses = numberOfGuesses + 1; numberOfGuesses += 1; numberOfGuesses ++; Also these ones: nextEvenNumber = nextEventNumber + 2; nextEvenNumber += 2;

Decrement Operator The following lines are equivalent! numberOfGuesses = numberOfGuesses - 1; numberOfGuesses -= 1; numberOfGuesses --; Also these ones: nextEvenNumber = nextEventNumber - 10; nextEvenNumber -= 10;

Increment/Decrement Operators They also work with multiplication and division The following lines are equivalent! doubleIt = doubleIt * 2; doubleIt *= 2; fractionIt = fraction / 5; doubleIt /= 5;

The for loop

The for Loop The for loop takes the form: for(initialization; test; update){ statement(s); } See Squares.java See TotalSales.java

Nested Loops

Nested Loops Example: for(int i = 0; i < 3; i++) { for(int j = 0; j < 4; j++) { loop statements; } See Clock.java // how can we create this output? 1 2 3 4 5 6 7 8 9 10 11 12

The break statement

I want to allow only 10 guesses The break statement I want to allow only 10 guesses int number = 5; int myGuess = 4; Scanner scan = new Scanner(System.in); int numberOfGuesses = 0; while (number != userGuess) { System.out.println(“Enter your guess: ”); int userGuess= scan.nextInt(); System.out.println(“Sorry, wrong number! Try again!”); numberOfGuesses++; } System.out.println(“Great Job! You got it!”); System.out.println(“It took “ + numberOfGuesses + “ guesses”);

The break statement Can we avoid the break? while (number != userGuess); { System.out.println(“Enter your guess: ”); int userGuess= scan.nextInt(); System.out.println(“Sorry, wrong number! Try again!”); numberOfGuesses++; if (numberOfGuesses >= 10) { System.out.println(“Game Over”); break; } System.out.println(“Do you want to play it again? “); Can we avoid the break?

The continue statement

Interviewing marathon runners For all people walking on the street If it is a runner, then interview Do I know how many people will pass? If it is not a runner, then skip to the next person walking So I’ll use the While loop for it!

The continue statement while (stillHavePeopleWalkingOnTheStreet()) { if (!PersonIsARunner) { continue; } performTheInterview(); numberOfRunnersInterviewed++;

Second Part Reading and Writing Data From/Into a File

Data Handling Reentering data all the time could get tedious for the user. The data can be read in from a file

Process of Writing data into a File Finding your car in the park lot (defining what file in the hard disc) Open the car door (opening the file to write) Let the woman go inside (write the data into the file) Close the door when she is inside (close the file after writing all the data)

Process of Reading data into a File It is the same process !

Types of File

(only some programs can read) Two Types of File Text Data (you can easily read) Binary Data (only some programs can read)

Reading Text Data From File

open a data stream between the file and your program Reading Data From File The Juice Bag is the Data File We need a straw! Your mouth is the program that wants the juice, opss, the data! We want the juice inside it! (We want to read the data) open a data stream between the file and your program How do we do that in real life?

The straw can be very long But remember, with the invention of internet, We might be opening a file that is located in the other side of the world!

Reading Data From a File In this course we will use the File and Scanner classes to read data from a file: Pass the name of the file as an argument to the File class constructor. The juice box (the data file) File myFile = new File("Customers.txt"); Scanner inputFile = new Scanner(myFile); The straw (the data stream) Pass the File object as an argument to the Scanner class constructor. Scanner inputFile = new Scanner(new File("Customers.txt"));

Reading Data From a File Code Example: // allow the user to enter the file name via keyboard Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); // get a reference to the data file File file = new File(filename); // get a data stream (straw) that connects your file // contents with your program Scanner inputFile = new Scanner(file); // Read a line from the file. String str = inputFile.nextLine(); // many other methods can be use to extract data: nextLine, nextInt, // nextDouble, etc.) // Close the file. inputFile.close();

Question How would I read all the contents of the file, instead of just one line? See FileReadDemo.java

Writing Text Data Into a File

Warning: if the file already exists, its contents will be erased Writing Text To a File Step #1: To open a file for text output you create an instance of the PrintWriter class. PrintWriter outputFile = new PrintWriter("StudentData.txt"); Pass the name of the file that you wish to open as an argument to the PrintWriter constructor. Warning: if the file already exists, its contents will be erased

The PrintWriter Class The PrintWriter class allows you to write data to a file using the print and println methods, as you have been using to display data on the screen. Just as with the System.out object, the println method of the PrintWriter class will place a newline character after the written data. The print method writes data without writing the newline character.

Open the file and get a stream The PrintWriter Class Open the file and get a stream PrintWriter outputFile = new PrintWriter("Names.txt"); outputFile.println("Chris"); outputFile.println("Kathryn"); outputFile.println("Jean"); outputFile.close(); Write data to the file Close the file

Appending Text to a File

Appending Text to a File To avoid erasing a file that already exists, create a FileWriter object in this manner: FileWriter fw = new FileWriter("names.txt", true); Then, create a PrintWriter object in this manner: PrintWriter fw = new PrintWriter(fw); The Juice Box! The Straw!

Specifying a File Location On a Windows computer, paths contain backslash (\) characters. PrintWriter outFile = new PrintWriter(“C:\\PriceList.txt"); On Unix/Linux the file paths contains forward slashes (/) to separate directories: PrintWriter outFile = new PrintWriter("/home/rharrison/names.txt");

Exceptions

The stream line that will connect the file and your code Reading Data From File Choose the juice box The stream line that will connect the file and your code Your code

Picking up a file can be risky! If we try to read data from an inexistent file the program will crash! We might be opening a file that is located in the other side of the world! How can we handle this situation? This operation is very risky! The file might not be there at all!

See ReadFirstLine.java Things to think about Is it possible to know (as programmer) during development time if the file that the user will specified in his input exists during run-time? This will cause an run-time error (or exception) that can cause your program to crash! There are ways of preventing your program to crash! See ReadFirstLine.java

Handling the unknown When something unexpected happens in a Java program, an exception is thrown The method that is executing when the exception is thrown must either handle the exception or pass it up To pass it up, the method needs a throws clause in the method header.

See ReadFirstLine.java Passing Exceptions Up To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. PrintWriter objects can throw an IOException, so we write the throws clause like this: public static void main(String[] args) throws IOException See ReadFirstLine.java

Any Questions?