Object-Oriented Programming in Java



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

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Chapter 2: Elements of Java

Install Java Development Kit (JDK) 1.8

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Using Files as Input/Output in Java 5.0 Applications

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Introduction to Java

Chapter 3. Input and output. 3.1 The System class

Building Java Programs

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Files and input/output streams

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

6.1. Example: A Tip Calculator 6-1

13 File Output and Input

Building Java Programs

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Comp 248 Introduction to Programming

Visit us at

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Introduction to Java. CS 3: Computer Programming in Java

Event-Driven Programming

D06 PROGRAMMING with JAVA

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

AP Computer Science File Input with Scanner

Basics of Java Programming Input and the Scanner class

AP Computer Science Java Mr. Clausen Program 9A, 9B

Software Development in Java

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Introduction to Programming

Lecture 5: Java Fundamentals III

Quick Introduction to Java

Reading Input From A File

Programmierpraktikum

CS 106 Introduction to Computer Science I

Programming Languages CIS 443

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

WRITING DATA TO A BINARY FILE

CS 106 Introduction to Computer Science I

JAVA - FILES AND I/O

CS 1302 Ch 19, Binary I/O

Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:

Pemrograman Dasar. Basic Elements Of Java

Week 1: Review of Java Programming Basics

Java CPD (I) Frans Coenen Department of Computer Science

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

JAVA.UTIL.SCANNER CLASS

Chapter 2 Introduction to Java programming

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Stream Classes and File I/O

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

More on Objects and Classes

Topic 11 Scanner object, conditional execution

Chapter 2 Elementary Programming

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

INPUT AND OUTPUT STREAMS

Sample CSE8A midterm Multiple Choice (circle one)

Assignment 4 Solutions

CS506 Web Design and Development Solved Online Quiz No. 01

Programming and Data Structures with Java and JUnit. Rick Mercer

Course Intro Instructor Intro Java Intro, Continued

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Some Scanner Class Methods

Moving from CS 61A Scheme to CS 61B Java

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Chapter 1 Java Program Design and Development

Homework/Program #5 Solutions

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

Building Java Programs

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

AP Computer Science Static Methods, Strings, User Input

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Introduction to Object-Oriented Programming

J a v a Quiz (Unit 3, Test 0 Practice)

1001ICT Introduction To Programming Lecture Notes

LAB4 Making Classes and Objects

Basics of I/O Streams and File I/O

What is an I/O Stream?

CSE 8B Midterm Fall 2015

Part I. Multiple Choice Questions (2 points each):

JAVA ARRAY EXAMPLE PDF

Text file I/O and simple GUI dialogues

Chapter 8. Living with Java. 8.1 Standard Output

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Introduction to Java Lecture Notes. Ryan Dougherty

Building Java Programs

Division of Informatics, University of Edinburgh

Creating a Simple, Multithreaded Chat System with Java

Arrays in Java. Working with Arrays

Computer Programming I

Explain the relationship between a class and an object. Which is general and which is specific?

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 public static void main(string[] args) Person p = new Person(); // error class Person String name; int age; Person(String na, int a) name = na; age = a;

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

Examples - method class Test public static void main(string[] args) Person p = new Person(); class Person String name; int age; void disply_age() 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.