The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.

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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
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.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
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.
Class Decimal Format ► Import package java.text ► Create DecimalFormat object and initialize ► Use method format ► Example: import java.text.DecimalFormat.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
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.
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.
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.
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:

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 2 Yesterday Variables and expressions Input/output Writing a whole program Any questions?

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 3 Today Classes and objects Graphical user interface (GUI) File input/output Formatting input and output

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 4 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 5 Classes What is a class? ♦ Data ♦ Operations Classes allow creation of new data types public class Student { }

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 6 Classes Vs. Data Types Abstract Descriptors ♦ Data Type ♦ Class Concrete Entities ♦ Variable ♦ Object

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 7 Inside a class Other classes Data types Methods (operations) public class Student { private String name; private int age; public void ComputeGrade(); }

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 8 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 9 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 10 Creating Objects We use the new operator to create objects, called instantiation Integer num; num = new Integer(78); parameter

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 11 Changing the Reference Var num = new Integer (50); The address of the newly-created object is stored in the already-created reference variable num

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 12 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"

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 13 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 14 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 UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 15 The class String String variables are reference variables Given String name; ♦ Equivalent Statements: name = new String(“Van Helsing”); name = “Van Helsing”;

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 16 name = “Van Helsing”; Van Helsing

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 17 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 18 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 19 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 20 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 21 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);

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 22 JOptionPane Methods showInputDialog str = JOptionPane.showInputDialog(strExpression); ♦ stores what the user enters into the String str showMessageDialog JOptionPane.showMessageDialog(parentComponent, strExpression, boxTitleString, messageType);

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 23 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 24 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 25 JOptionPane Example JOptionPane.showMessageDialog (null, "Hello World!", "Greetings", JOptionPane.INFORMATION_MESSAGE);

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 26 UsingGUI.java example

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 27 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 28 Reading From Text Files String file = "data.dat"; BufferedReader inFile = new BufferedReader (new FileReader (file)); String line = inFile.readLine(); inFile.close();

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 29 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 30 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 31 Writing To Text Files String file = "outfile.dat"; PrintWriter outFile = new PrintWriter (new FileWriter (file)); outFile.print ("Hi"); outFile.println(" There!"); outFile.close();

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 32 User Input BufferedReader ♦ reads everything as a string Integer.parseInt ♦ only handles one integer in the string How to handle? Enter 3 numbers:

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 33 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 34 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 UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 35 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()

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 36 Tokenize.java example separated by spaces separated by commas

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 37 Formatting the Output of Decimal Numbers float: defaults to 6 decimal places double: defaults to 15 decimal places

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 38 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

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 39 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));_______

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie 40 To do Ch. 3 examples: ♦ Movie Ticket Sale ♦ Donation to Charity ♦ Student Grade Homework 2 due tomorrow. Homework 3 due next Tuesday. Read Ch. 4