Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Similar documents
Week 7 - More Java! this stands for the calling object:

Week 6: Review. Java is Case Sensitive

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

Fall 2017 CISC124 10/1/2017

Fall 2017 CISC124 9/27/2017

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

Streams and File I/O

Fundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

HST 952. Computing for Biomedical Scientists Lecture 8

Full file at

A variable is a name for a location in memory A variable must be declared

Lesson 3: Accepting User Input and Using Different Methods for Output

Simple Java Input/Output

1.00 Lecture 30. Sending information to a Java program

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

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

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

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

Data Structures. 03 Streams & File I/O

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

Oct Decision Structures cont d

Pace University. Fundamental Concepts of CS121 1

Program Fundamentals

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Section 2: Introduction to Java. Historical note

Expanded Guidelines on Programming Style and Documentation

Chapter 2: Programming Concepts

Full file at

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

AP Computer Science A

IT101. File Input and Output

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Getting started with Java

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Using Java Classes Fall 2018 Margaret Reid-Miller

Lecture 2 Tao Wang 1

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Dining philosophers (cont)

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

Streams and File I/O

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

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

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

PIC 20A The Basics of Java

TUGCE KEMEROZ - ASLI OZKAN - AYSE TARTAN. Week 12/02/ /02/2007 Lecture Notes:

Basics of Java Programming

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

File Input/Output. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

USING LIBRARY CLASSES

CS11 Java. Fall Lecture 1

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

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

ECE 122 Engineering Problem Solving with Java

Give one example where you might wish to use a three dimensional array

Introduction to Programming Using Java (98-388)

Supplement D: Expanded Guidelines on Programming Style and Documentation

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

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

4 Programming Fundamentals. Introduction to Programming 1 1

File I/O Array Basics For-each loop

APPENDIX A: SUMMARY OF IMPORTANT JAVA FEATURES

CS 251 Intermediate Programming Java I/O Streams

Classes Basic Overview

PIC 20A Streams and I/O

CS Exam 1 Review Suggestions

Exceptions and Working with Files

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Streams and File I/O

CSPP : Introduction to Object-Oriented Programming

Lecture Notes for CS 150 Fall 2009; Version 0.5

First Name: AITI 2004: Exam 2 July 19, 2004

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Streams and File I/O

CT 229 Fundamentals of Java Syntax

Byte and Character Streams. Reading and Writing Console input and output

Visual C# Instructor s Manual Table of Contents

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Java Bytecode (binary file)

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

CSE 11 Style Guidelines

CSC Java Programming, Fall Java Data Types and Control Constructs

Programming Languages and Techniques (CIS120)

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Text User Interfaces. Keyboard IO plus

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

Introduction Unit 4: Input, output and exceptions

Key Differences Between Python and Java

Full file at

Transcription:

Week 8 Variables of class Type - Correction! Libraries/Packages String Class, reviewed Screen Input/Output, reviewed File Input/Output Coding Style Guidelines A simple class: Variables of class Type public class Student { private int age; private boolean is_awake; private boolean is_reading_paper; public Student (int n, boolean awake, boolean paper) { set_student(n, awake, paper); } // end default constructor public void set_student (int n, boolean awake, boolean paper) { age = n; is_awake = awake; is_reading_paper = paper; } // end set_student method // more methods } // end Student class APSC142 - Prof.McLeod 1 APSC142 - Prof.McLeod 2 Variables of class Type, Cont. What would be returned by: artsstudent = apscstudent; (apscstudent == artsstudent)? Variables of class Type, Cont. What would be returned by: (apscstudent == artsstudent)? true (not false as in last week s lecture!) Memory Location Variable Name Value 1048 apscstudent 5012 1120 artsstudent 5012 More memory locations When the equality operator is used to compare objects, it only compares the memory locations referenced by the two objects. Suppose we tried: 5012 8068 age 32 is_awake true is_reading_paper false (methods, etc ) More memory locations age 22 is_awake false is_reading_paper false (methods, etc ) Student test1 = new Student(20, true, true); Student test2 = new Student(20, true, true); (test1 == test2) // would return false test1 = test2; // match memory locations (test1 == test2) // now returns true // regardless of attribute values Should define an equals method as member of Student class. APSC142 - Prof.McLeod 3 APSC142 - Prof.McLeod 4 1

Libraries or Packages A package is a collection of classes that are grouped together under one package name. The classes are still in separate files and follow the same naming rules, as always. The first line in a class that is to be included in a package must be: package package_name; package_name must include the directory path from that given by the CLASSPATH DOS environmental variable (internal to JBuilder2). For example, if your package classes are in C:\JBuilder2\myclasses\myStuff\utilities then package_name would be mystuff.utilities. In order to use all these classes a program uses an import statement: import mystuff.utilities.*; Libraries or Packages, Cont. The import statement must also be right at the top of the program, before the class definition line. The * at the end tells the import statement to import all classes - otherwise you can specify which classes you want to import. Packages that are often imported for simple input/output (screen or file) are java.io.* and java.util.*. GUI tools are available from Swing: javax.swing.* and/or AWT: java.awt.* and java.awt.event.*. Essentially, importing packages allows you to extend the Java language with the tools that you need for your purposes. APSC142 - Prof.McLeod 5 APSC142 - Prof.McLeod 6 String literals: String Class, reviewed Escape Characters: String Class, Cont. Press <enter> to continue. String variable declaration: String teststuff; or: String teststuff = A testing string. ; String concatenation ( addition ): String teststuff = Hello ; System.out.println(testStuff + to me! ); Would print the following to the DOS window: Hello to me! \ Double quote \ Single quote \\ Backslash \n Go to beginning of next line \r Go to beginning of current line \t Tab character For example: String teststuff = Line1\nLine2 ; System.out.println(testStuff); Would print the following to the DOS window: Line1 Line2 APSC142 - Prof.McLeod 7 APSC142 - Prof.McLeod 8 2

String Class, Cont. String methods include: length() equals(otherstring) equalsignorecase(otherstring) tolowercase() touppercase() trim() charat(position) substring(start) substring(start, End) indexof(searchstring) replace(oldchar, newchar) startswith(prefixstring) endswith(suffixstring) Wrapper Class Methods for String/Number Conversions Integer.parseInt(String value) // returns // an int Integer.toString(int value) // returns a // String Double.valueOf(String value) // returns a // double Double.toString(double value) // returns a // String Remember that wrapper class methods are all static. APSC142 - Prof.McLeod 9 APSC142 - Prof.McLeod 10 Screen Input/Output, reviewed To print to the screen (a DOS window): System.out.print( Good Morning ); // no LF System.out.println( Class! ); // appends LF print and println are overloaded methods, and can take arguments of any primitive type, String class, or object. To get input from the screen (from the user): SavitchIn.readLine() // returns a String SavitchIn.readLineInt() // returns int SavitchIn.readLineDouble() // returns double SavitchIn.readLineNonwhiteChar() // returns //first non-space char All SavitchIn methods are static. The SavitchIn class uses java.io and java.util libraries. File Input/Output File input means reading from a file into memory. File output means writing to a file from memory. SavitchIn does not include any methods for file input/output. We will be concerned with input/output for text files only (as opposed to binary files). Text files can be easily viewed, edited and/or created with Notepad, or any other text editor. Need to use methods and classes from the java.io library, so you must have an import statement as the first line in your program file: import java.io.*; APSC142 - Prof.McLeod 11 APSC142 - Prof.McLeod 12 3

Inside your method: File Output For example: File Output, Cont. PrintWriter outputstream = new PrintWriter( new FileOutputStream(fileName)); PrintWriter dataout = new PrintWriter( new FileOutputStream( Data.txt )); PrintWriter and FileOutputStream are classes from java.io. outputstream is a variable name that you choose. filename is a String literal or String variable representing the name of a text file. As used above, if filename does not exist, it is created. If filename does exist, the previous content of the file is overwritten. To append to an existing file, use: PrintWriter outputstream = new PrintWriter( new FileOutputStream(fileName, true)); To write text to the file use print() or println() methods: dataout.print( No LF after this line! ); dataout.println( This one has a LF. ); When finished writing to file, close it using: dataout.close(); Closing a file immediately after writing helps to prevent corruption of your file, if your program crashes before it would normally terminate. APSC142 - Prof.McLeod 13 APSC142 - Prof.McLeod 14 Inside your method: File Input To read from the file: File Input BufferedReader inputstream = new BufferedReader(new FileReader(fileName)); BufferedReader and FileReader are classes from java.io. iputstream is a variable name that you choose. filename is a String literal or String variable representing the name of a text file. For example: String inputline = null; inputline = indata.readline().trim(); // returns trimmed String value to // inputline. // entire line is read. // null is returned if at end of file. When done, close the file: indata.close(); BufferedReader indata = new BufferedReader(new FileReader( Data.txt )); APSC142 - Prof.McLeod 15 APSC142 - Prof.McLeod 16 4

File Input/Output, Cont. Note that the filename String can contain a full or relative path, along with the filename. The path and filename must be legal for the operating system in use. The techniques described above are for textonly sequential file operations. Sequential means that you can only add data to the end of the file. Reading the file must start at the beginning of the file and progress towards the end. Random input/output can be done with binary files. You can read/write to any position in the file. When a file is not found (for input), or cannot be opened (for output), an exception is thrown by the java.io classes used. In more advanced programs, these exceptions can be caught and handled. Coding Style Guidelines The purpose of adding white space and comments to your code is to make it easier to maintain, as well as making it more easily understood by another programmer. Properly formatted comments can also be used to generate external documentation (using javadoc ). But don t go overboard! Too many comments swamp out the code. Don t repeat yourself in comments! Be concise! Use descriptive variable names, that might use one, two or possibly even three words - don t use a sentence! For example: num_students is much better than: variable_to_keep_track_of_the_number_of_students APSC142 - Prof.McLeod 17 APSC142 - Prof.McLeod 18 Coding Style Guidelines, Cont. 1. Variable Names Use descriptive variable names (method names will probably contain a verb). Use all uppercase for constants. Primitive type variable names start with a lowercase letter, object names start with an upper case letter. Use _ to space out the variable name. 2. Indentation Use a three-space indent (JBuilder default). Indent code in any block. Line up braces ({}) as follows: while (total < 25) { } total += 5; System.out.println("The total is " + total); Line up else with corresponding if: if (num_students > 100) statement; else statement; Coding Style Guidelines, Cont. 3. Spacing Put one space after every comma in a parameter list. Put one space on either side of a binary operator (like: +, -, <, >=, etc.) Do not put a space after ( or before ). Do not put a space before ;. Put one space before (. Do not put a space before [ 4. Comments Add comments as you complete logical units of your code - don t wait until you are finished. Assume that your reader is familiar with the Java language, but has no idea of how your program works. Make sure your comments keep up with code changes. If you use a block comment (/*.*/) then add a * to the left of each line. Comment any variable name that is not completely self-explanatory. APSC142 - Prof.McLeod 19 APSC142 - Prof.McLeod 20 5

Coding Style Guidelines, Cont. 4. Comments, Cont. A comment should be aligned with the block it is describing. Block comments should be used to describe each class and method. Include author name(s), and date, version or revision number (for larger projects) in the comment describing a class. It should also describe the purpose of the class. Method comments should include a description of what the method does, and the algorithm used. The main method comment should describe the overall purpose of the main method and what input & output should be provided and expected. Add short comments to the code body of a method where appropriate. Provide a brief explanation of logical units of code. When you are coding, you can add comments to remind yourself of an area that will need additional work after another module is completed, for example. Add an in-line comment after each close } to indicate what they close. Coding Style Guidelines, Cont. 5. External Documentation At present, you append the sample DOS output of your program to the end of your program as a comment. That is all that is required for this course. External documentation is supplied for a user of your code. It is less technical and more descriptive. It describes the purpose of the program and describes the user interface (but not the implementation!). The description would include the input and output of the program, and the meanings of various error messages, etc. You must assume that your user knows nothing about programming, and has only fundamental computer skills. APSC142 - Prof.McLeod 21 APSC142 - Prof.McLeod 22 6