CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2014.

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

Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
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
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
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.
18 File handling1June File handling CE : Fundamental Programming Techniques.
File I/O There’s more to life than the keyboard. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction.
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.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
CS1101: Programming Methodology Aaron Tan.
CS0007: Introduction to Computer Programming File IO and Recursion.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
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 5 Loops.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
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.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
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.
Chapter 5: Control Structures II
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.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
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.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Loops and Files. 5.1 The Increment and Decrement Operators.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
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.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
Slides by Evan Gallagher
CMSC 202 Text File I/O.
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
Introduction to programming in java
INTERMEDIATE PROGRAMMING USING JAVA
Lecture 4- Loops and Files
I/O Basics.
Chapter 4: Loops and Files
Chapter 4: Loops and Files by Tony Gaddis and Godfrey Muganda
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Dr. Sampath Jayarathna Cal Poly Pomona
Ch.4 – 5 Topics The auto Increment and Decrement Operators
Presentation transcript:

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2014

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

The While Loop Presidential Towers Stair Climb - Reference Video

The While Loop While Loop Syntax: 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!”);

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

“Guess the number” game We will make the program to randomly generates a number from 0 to 9 Then the program will keep asking the user to guess what the secret number is (with the Scanner/keyboard input) If the user guess wrong, the program gives a message and keeps asking the user to try again When the user gets the right number, the program prints a message congratulating the user, shows how many guesses he/she took, and exits

Program Features How do I implement this game? The program will need to: Define a “secret” number Have a way to allow the user to enter a number Check the user number with the secret number If numbers don’t match, then repeat the last two items If numbers match quit game

“Guess my number” game Scanner keyboard= new Scanner(System.in); int numberOfGuesses = 0; int theHiddenNumber = 5; int userGuess = 4; while (userGuess != number) { System.out.println(“Enter your guess: ”); userGuess = keyboard.nextInt(); if (userGuess != theHiddenNumber) { System.out.println(“Sorry, wrong number! Try again!”); } numberOfGuesses = numberOfGuesses + 1; } System.out.println(“Great Job! You got it!”); System.out.println(“It took “ + numberOfGuesses + “ guesses”); I don’t like that!

The Do-While Loop Syntax: do { statement(s); } while (condition); Example: int number = 5; Scanner scan = new Scanner(System.in); int numberOfGuesses = 0; do { System.out.println(“Enter your guess: ”); int userGuess= scan.nextInt(); if (number != userGuess) { System.out.println(“Sorry, wrong number! Try again!”); } numberOfGuesses = numberOfGuesses + 1; } while (number != userGuess);

Time Out! int number = 5; How can I generate a number randomly for my program?

Time Out #2 numberOfGuesses = numberOfGuesses + 1; Is there another way of increment a variable by 1?

Increment operators int number = 5; Int userGuess = 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 = numberOfGuesses + 1; } System.out.println(“Great Job! You got it!”); System.out.println(“It took “ + numberOfGuesses + “ guesses”);

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;

4-22 The for Loop The for loop takes the form: for(initialization; test; update) { statement(s); } Example: int maxNumber = 5; for(int i = 0; i < maxNumber; i++) { System.out.println(“The square of “ + i + “ is “ + i*i); } See example: Squares.java and TotalSales.javaSquares.java TotalSales.java

Nested Loops Example: slides from Editor\Chapter 04\Clock.javaslides from Editor\Chapter 04\Clock.java Example: for(int i = 0; i < 3; i++) for(int j = 0; j < 4; j++) loop statements; Let’s generate the following 2D matrix

Going a little further Run the guess game Debugging the code in NetBeans What happens if the user provides a wrong input, like “a” instead of a number? Exception handling Still problems in the code, let’s debug even further.

The break statement public static void main(String[] args) { int number = 5; int userGuess = 4; Scanner scan = new Scanner(System.in); int numberOfGuesses = 0; while (number != userGuess) { System.out.println("Enter your guess: "); 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"); } I want to allow only 10 guesses

The break statement 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?

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

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

Let’s fix the Game program Use the “continue” in case the user provides an invalid input

Generating random number opicAction.do?Id=62

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 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) Finding your car in the park lot (defining what file in the hard disc)

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

Time Out What are the most common data types to write/read to/from a file? Talking about writing and reading data, it comes to my mind a question…

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

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

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

4-43 Reading Data From a File You use the File class and the Scanner class to read data from a file: File myFile = new File("Customers.txt"); Scanner inputFile = new Scanner(myFile); Pass the name of the file as an argument to the File class constructor. Pass the File object as an argument to the Scanner class constructor. The juice box (the file itself) The straw (the data stream)

4-44 Reading Data From a File Code Example: Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); File file = new File(filename); Scanner inputFile = new Scanner(file); The lines above: Creates an instance of the Scanner class to read from the keyboard Prompt the user for a filename Get the filename from the user Create an instance of the File class to represent the file Create an instance of the Scanner class that reads from the file

4-45 Reading Data From a File Once an instance of Scanner is created, data can be read using the same methods that you have used to read keyboard input ( nextLine, nextInt, nextDouble, etc). Example: // Open the file. File file = new File("Names.txt"); Scanner inputFile = new Scanner(file); // Read a line from the file. String str = inputFile.nextLine(); // Close the file. inputFile.close();

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

4-48 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, it will be erased and replaced with a new file.

4-49 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.

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

4-52 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!

4-53 Specifying a File Location On a Windows computer, paths contain backslash ( \ ) characters. PrintWriter outFile = new PrintWriter(“C:\\PriceList.txt"); Fortunately, Java allows Unix style filenames using the forward slash ( / ) to separate directories: PrintWriter outFile = new PrintWriter("/home/rharrison/names.txt");

4-54 Detecting The End of a File The Scanner class’s hasNext() method will return true if another item can be read from the file. // Open the file. File file = new File(filename); Scanner inputFile = new Scanner(file); // Read until the end of the file. while (inputFile.hasNext()) { String str = inputFile.nextLine(); System.out.println(str); } // close the file inputFile.close();// close the file when done. See example: slides from Editor\Chapter 04\FileReadDemo.javaslides from Editor\Chapter 04\FileReadDemo.java

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

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

4-58 Things to think about It is not possible to know (as programmer) during development time if the file that the user will specify in his input during run-time exists. 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!

Handling the unknown When something unexpected happens in a Java program, an exception is thrown The method that is being executed when the exception occurs must either handle the exception itself or pass it to the caller method Real life example: you at the supermarket not finding the brand of orange juice your wife always buy. Either you make your mind and buy other brand or you call your wife and ask her to handle this decision. To pass it up, the method needs a throws clause in the method header.

4-60 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 Example: ReadFirstLine.javaReadFirstLine.java

Any Questions? 62

Lab 02