Object-Oriented Programming in Java

Similar documents
Chapter 4: Loops and Files

Chapter 4: Loops and Files

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

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

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

CSCI 1103: File I/O, Scanner, PrintWriter

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

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

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

Computational Expression

Dec. 16/ Deciding Which Loop to Use

File I/O Array Basics For-each loop

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

Text User Interfaces. Keyboard IO plus

CSCI 1103: File I/O, Scanner, PrintWriter

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

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

File Input and Output Review CSC 123 Fall 2018 Howard Rosenthal

Simple Java Input/Output

AP Computer Science Unit 1. Programs

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

Midterm Examination (MTA)

Section 2.2 Your First Program in Java: Printing a Line of Text

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

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

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

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.

Java Input/Output. 11 April 2013 OSU CSE 1

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CSIS 10A Assignment 4 SOLUTIONS

ACS-1903 Basic program structure Feb 16, 2017

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

COMP102: Test 1 Model Solutions

Elementary Programming

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

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

Reading Input from Text File

Simple Java Reference

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

Object Oriented Programming. Java-Lecture 1

Program 12 - Spring 2018

Introduction to Java Applications; Input/Output and Operators

Formatted Output / User IO

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

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

Fundamentals of Programming Data Types & Methods

CS Programming I: File Input / Output

IT101. File Input and Output

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

We now start exploring some key elements of the Java programming language and ways of performing I/O

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Full file at

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CS 251 Intermediate Programming Java I/O Streams

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

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

STUDENT LESSON A7 Simple I/O

Exceptions Handeling

CS Programming I: File Input / Output

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

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

Excep&ons and file I/O

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

Basic Computation. Chapter 2

Input-Output and Exception Handling

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

CS 302: Introduction to Programming

CHAPTER 2 Java Fundamentals

Full file at

MIDTERM REVIEW. midterminformation.htm

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

First Java Program - Output to the Screen

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Pace University. Fundamental Concepts of CS121 1

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

4. If the following Java statements are executed, what will be displayed?

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

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

ing execution. That way, new results can be computed each time the Class The Scanner

Chapter 2: Basic Elements of Java

Unit 10: exception handling and file I/O

Using Java Classes Fall 2018 Margaret Reid-Miller

COMP102: Test. 26 April, 2006

Lab5. Wooseok Kim

Classes and Objects Part 1

Full file at

Programming with Java

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

A+ Computer Science -

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

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

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

Object-Oriented Programming in Java

Transcription:

CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio Grande Valley

Examples - class class Test public static void main(string[] args) Person p = new Person(); class Person String name; int age;

Examples - constructor class Test class Person public static void main(string[] args) String name; int age; Person(String na, int a) Person p = new Person(); // error name = na; age = a;

Examples - constructor class Test class Person public static void main(string[] args) String name; int age; Person(String na, int a) Person p = new Person( Mike, 18); // no error name = na; age = a;

class Test Examples - method class Person public static void main(string[] args) String name; int age; void disply_age() Person p = new Person(); System.out.println(age);

dot operator to access members class Test class Person public static void main(string[] args) String name; int age; void disply_age() Person p = new Person(); p.age = 21; p.display_age(); System.out.println(age);

final

Creating Named Constants with final Constants keep the program organized and easier to maintain. Constants are identifiers that can hold only a single value. Constants are declared using the keyword final. Constants need not be initialized when declared; however, they must be initialized before they are used or a compiler error will be generated.

Creating Named Constants with final Once initialized with a value, constants cannot be changed programmatically. By convention, constants are all upper case and words are separated by the underscore character. For example: final double CAL_SALES_TAX = 0.0725;

printf

Setting the Field Width A format specifier may also include a field width. Here is an example: int number = 9; System.out.printf("The value is %6d\n", number); The format specifier %6d indicates that the argument number should be printed in a field that is 6 places wide. If the value in number is shorter than 6 places, it will be right justified. Here is the output of the code. 123456 The value is 9 If the value of the argument is wider than the specified field width, the field width will be expanded to accommodate the value.

Using Field Widths to Print Columns Field widths can help when you need to print values aligned in columns. For example, look at the following code: int num1 = 97654, num2 = 598; int num3 = 86, num4 = 56012; int num5 = 246, num6 = 2; System.out.printf("%7d %7d\n", num1, num2); System.out.printf("%7d %7d\n", num3, num4); System.out.printf("%7d %7d\n", num5, num6); This code displays the values of the variables in a table with three rows and two columns. Each column has a width of seven spaces. Here is the output for the code: 97654 598 86 56012 246 2 1 2 3 4 5 6 7 1 2 3 4 5 6 7

Printing Formatted Floating- Point Values If you wish to print a floating-point value, use the %f format specifier. Here is an example: double number = 1278.92; System.out.printf("The number is %f\n", number); This code produces the following output: The number is 1278.920000 You can also use a field width when printing floating-point values. For example the following code prints the value of number in a field that is 18 spaces wide: System.out.printf("The number is %18f\n", number);

Printing Formatted Floating- Point Values In addition to the field width, you can also specify the number of digits that appear after the decimal point. Here is an example: double grosspay = 874.12; System.out.printf("Your pay is %.2f\n", grosspay); In this code, the %.2f specifier indicates that the value should appear with two digits after the decimal point. The output of the code is: Your pay is 874.12 1 2

File I/O

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 files or output files. Files: Files have to be opened. Data is then written to the file. The file must be closed prior to program termination. In general, there are two types of files: binary text

Writing Text To a File To open a file for text output you create an instance of the PrintWriter class. PrintWriter outputfile = new PrintWriter("test.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.

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.

The PrintWriter Class Open the file. PrintWriter outputfile = new PrintWriter("Names.txt"); outputfile.println("chris"); outputfile.println("kathryn"); outputfile.println("jean"); outputfile.close(); Close the file. Write data to the file.

The PrintWriter Class To use the PrintWriter class, put the following import statement at the top of the source file: import java.io.*;

Exceptions 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 the line. Handling the exception will be discussed later. To pass it up the line, the method needs a throws clause in the method header.

Exceptions 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

Example - PrintWriter import java.io.*; public class Hello public static void main(string[ ] args) throws IOException PrintWriter pw = new PrintWriter("test.txt"); pw.println("hello, Dr. Kim."); pw.close();

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 pw = new PrintWriter(fw);

Example - FileWriter import java.io.*; public class Hello public static void main(string[ ] args) throws IOException FileWriter fw = new FileWriter("test.txt", true); //PrintWriter pw = new PrintWriter("test.txt"); PrintWriter pw = new PrintWriter(fw); pw.println("hello, Dr. Kim."); pw.close();

Specifying a File Location On a Windows computer, paths contain backslash (\) characters. Remember, if the backslash is used in a string, it is a special character so you must use two of them (\\): FileWriter fw = new FileWriter("C:\\test.txt", true);

Specifying a File Location This is only necessary if the backslash is in a string literal. If the backslash is in a String object then it will be handled properly. Fortunately, Java allows Unix style filenames using the forward slash (/) to separate directories: FileWriter fw = new FileWriter("./test.txt", true);

Reading Data From a File You use the File class and the Scanner class to read data from a file: Pass the name of the file as an argument to the File class constructor. File f1= new File("Customers.txt"); Scanner s1 = new Scanner(f1); Pass the File object as an argument to the Scanner class constructor.

Reading Data From a File Scanner s1 = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = s1.nextline(); File file = new File(filename); Scanner s2 = 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

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). // Open the file. File file = new File("Names.txt"); Scanner s1 = new Scanner(file); // Read a line from the file. String str = s1.nextline(); // Close the file. s1.close();

Example Read File import java.io.*; import java.util.scanner; public class Hello public static void main(string[] args) throws IOException File f1 = new File("C:\\test.txt"); PrintWriter pw = new PrintWriter(new FileWriter(f1,true)); pw.println("hello, Dr. Kim."); pw.println("how are you?"); pw.close(); Scanner s1 = new Scanner(f1); System.out.println(s1.nextLine()+" "+s1.nextline()); s1.close();

Exceptions The Scanner class can throw an IOException when a File object is passed to its constructor. So, we put a throws IOException clause in the header of the method that instantiates the Scanner class.

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 s1 = new Scanner(file); // Read until the end of the file. while (s1.hasnext()) String str = s1.nextline(); System.out.println(str); s1.close();// close the file when done.