COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
Advertisements

Java Programming Strings Chapter 7.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Introduction to Objects and Input/Output
Chapter 2 - Introduction to Java Applications
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
COMP 14 Introduction to Programming Mr. Joshua Stough February 7, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 28, 2005.
COMP 14 Introduction to Programming Mr. Joshua Stough February 2, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
Class Decimal Format ► Import package java.text ► Create DecimalFormat object and initialize ► Use method format ► Example: import java.text.DecimalFormat.
Fundamental Programming Structures in Java: Strings.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Chapter 2 - Introduction to Java Applications
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
Chapter 3: Introduction to Objects and Input/Output.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Warm-Up: Monday, March 3 List all devices you can think of that can be used to input information into the computer.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CIS 260: App Dev I. 2 Objects and Reference Variables n Predefined Java classes you have used:  String —for defining and manipulating strings  Integer.
Using Classes BCIS 3680 Enterprise Programming. Overview 2  Using Classes  Using premade classes for input and output  Display output: System, JOptionPane.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
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.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Textbook: Data Structures and the Java Collections Framework 3rd Edition by William Collins William Collins.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Objectives ► Become familiar with the class String ► ► Learn how to use input and output dialog boxes in a program ► ► Learn how to tokenize the input.
1/23: Java Modular Components Identifiers: naming requirements for Java variables & objects Stepping out of the MS-DOS window: The Java Modular Component:
Lecture 2 Objectives Learn about objects and reference variables.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
1 CHAPTER 3 StringTokenizer. 2 StringTokenizer CLASS There are BufferedReader methods to read a line (i.e. a record) and a character, but not just a single.
GUI Graphical User Interface Each onscreen component and window is an object Object interaction makes communication and scoping challenging Event-driven.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009.
Files and console applications Chapter 17 This chapter explains: What a file is How to read and write to files How to manipulate folder paths and file.
 2005 Pearson Education, Inc. All rights reserved. 1 Introduction to Classes and Objects.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CSC 142 H 1 CSC 142 Standard input/output. CSC 142 H 2 Console Ouput  Use the static PrintStream object out in System System.out.println("Hello, world");
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
Casting, Wrapper Classes, Static Methods, JOptionPane Class.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Java Programming Lecture 2
3 Introduction to Classes and Objects.
Outline Creating Objects The String Class Packages Formatting Output
Introduction to Classes and Objects
2.5 Another Java Application: Adding Integers
COMP 14 Introduction to Programming
Chapter 3: Introduction to Objects and Input/Output
Chapter 2 - Introduction to Java Applications
Chapter 3: Introduction to Objects and Input/Output
Introduction to Java Programming
Presentation transcript:

COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004

Last Friday Variables and expressions Input/output Writing a whole program Any questions?

Today Classes and objects Graphical user interface (GUI) File input/output Formatting input and output

Classes In the Java programming language: –a program is made up of one or more classes –a class contains one or more methods –a method contains program statements

Classes What is a class? –Data –Operations Classes allow creation of new data types public class Student { }

Classes Vs. Data Types Abstract Descriptors –Data Type –Class Concrete Entities –Variable –Object

Inside a class Other classes Data types Methods (operations) public class Student { private String name; private int age; public void ComputeGrade(); }

Primitive Variables int x = 45; x is associated with a memory location. It stores the value 45 When the computer sees x, it knows which memory location to look up the value in

Reference Variables Integer num; The memory location associated with num can store a memory address. The computer will read the address in num and look up an Integer object in that memory location

Creating Objects We use the new operator to create objects, called instantiation Integer num; num = new Integer(78); parameter

Changing the Reference Var num = new Integer (50); The address of the newly-created object is stored in the already-created reference variable num

Garbage Collection What happened to the memory space that held the value 78? If no other reference variable points to that object, Java will "throw it away"

System.out.println (”Hello World!”); object method information provided to the method (parameters) Using Objects System.out object –represents a destination to which we can send output Example: –println method dot operator

Questions 1.True or False. A primitive variable is a variable that stores the address of a memory space. 2.The operator is used to create a class object. 3.In Java, the operator is used to access members of a class. It separates the class (or object) name from the method name. 4.True or False. Class objects are instances of that class. new dot (.) False True

The class String String variables are reference variables Given String name; –Equivalent Statements: name = new String(“Van Helsing”); name = “Van Helsing”;

Van Helsing

The class String The String object is an instance of class string The value “Van Helsing” is instantiated The address of the value is stored in name The new operator is unnecessary when instantiating Java strings String methods are called using the dot operator

Common String Methods String(String str) –constructor –creates and initializes the object char charAt(int index) –returns char at the position specified by index (starts at 0) int indexOf(char ch) –returns the index of the first occurrence of ch int compareTo(String str) –returns negative if this string is less than str –returns 0 if this string is the same as str –returns positive if this string is greater than str

Common String Methods boolean equals(String str) –returns true if this string equals str int length() –returns the length of the string String replace(char toBeReplaced, char replacedWith) –returns the string in which every occurrence of toBeReplaced is replaced with replacedWith String toLowerCase() –returns the string that is the the same as this string, but all lower case String toUpperCase() –returns the string that is the same as this string, but all upper case

String Examples String str = “Van Helsing"; System.out.println (str.length()); System.out.println (str.charAt(2)); System.out.println (str.indexOf(‘s'); System.out.println (str.toLowerCase()); n 11 7 van helsing

Using Dialog Boxes for I/O Use a graphical user interface (GUI) class JOptionPane –Contained in package javax.swing –showInputDialog allows user to input a string from the keyboard –showMessageDialog allows the programmer to display results Program must end with System.exit(0);

JOptionPane Methods showInputDialog str = JOptionPane.showInputDialog(strExpression); –stores what the user enters into the String str showMessageDialog JOptionPane.showMessageDialog(parentComponent, strExpression, boxTitleString, messageType);

showMessageDialog parentComponent –parent of the dialog box –we'll use null StrExpression –what you want displayed in the box boxTitleString –title of the dialog box messageType –what icon will be displayed

messageType JOptionPane.ERROR_MESSAGE –error icon JOptionPane.INFORMATION_MESSAGE –information icon JOptionPane.PLAIN_MESSAGE –no icon JOptionPane.QUESTION_MESSAGE –question mark icon JOptionPane.WARNING_MESSAGE –exclamation point icon

JOptionPane Example JOptionPane.showMessageDialog (null, "Hello World!", "Greetings", JOptionPane.INFORMATION_MESSAGE);

UsingGUI.java example

Reading From Text Files Similar to reading from the keyboard Create a BufferedReader object, but use a FileReader object instead of InputStreamReader Create BufferedReader object inside the main method instead of outside Substitute the name of the file for System.in When finished reading from the file, we need to close the file: –BufferedReader close() method

Reading From Text Files String file = "data.dat"; BufferedReader inFile = new BufferedReader (new FileReader (file)); String line = inFile.readLine(); inFile.close();

Exceptions FileNotFoundException –if the file specified to open was not found IOException –some other I/O exception public static void main (String[] args) throws FileNotFoundException, IOException

Writing To Text Files Similar to reading from text files Use FileWriter and PrintWriter instead of FileReader and BufferedReader PrintWriter –methods include print() and println(), just like those we used in System.out Like reading, we need to close the file when we're done –PrintWriter close() method

Writing To Text Files String file = "outfile.dat"; PrintWriter outFile = new PrintWriter (new FileWriter (file)); outFile.print ("Hi"); outFile.println(" There!"); outFile.close();

User Input BufferedReader –reads everything as a string Integer.parseInt –only handles one integer in the string How to handle? Enter 3 numbers:

The StringTokenizer Class tokens –elements that comprise a string tokenizing –process of extracting these elements delimiters –characters that separate one token from another StringTokenizer class –defined in the java.util package –used to separate a string into tokens

Tokens and Delimiters “The weekend is over" "Bart:Lisa:Homer:Marge" delimiter: ' ' (space) tokens: “The’’ “weekend’’ “is’’ “over’’ delimiter: ':' tokens: "Bart" "Lisa" "Homer" "Marge"

The StringTokenizer Class Default delimiters: –space, tab, carriage return, new line Methods –StringTokenizer (String str) –StringTokenizer (String str, String delimits) –String nextToken() –boolean hasMoreTokens() –int countTokens()

Tokenize.java example separated by spaces separated by commas

Formatting the Output of Decimal Numbers float: defaults to 6 decimal places double: defaults to 15 decimal places

class DecimalFormat Import package java.text Create DecimalFormat object and initialize DecimalFormat fmt = new DecimalFormat (formatString); FormatString –"0.00" - limit to 2 decimal places, use 0 if there's no item in that position –"0.##" - limit to 2 decimal places, no trailing 0 Use method format –rounds the number instead of truncating Result of using DecimalFormat is a String

Examples DecimalFormat twoDecimal = new DecimalFormat("0.00"); DecimalFormat fmt = new DecimalFormat("0.##"); System.out.println (twoDecimal.format(56.379)); System.out.println (fmt.format(56.379)); System.out.println (twoDecimal.format(.3451)); System.out.println (fmt.format(.3451)); System.out.println (twoDecimal.format(.3)); System.out.println (fmt.format(.3));

To do Ch. 3 examples: –Movie Ticket Sale –Donation to Charity –Student Grade Homework 3 due Thursday night. Read Ch. 4