Unformatted text preview:

COMP 14 Introduction to ProgrammingLast FridayTodayClassesSlide 5Classes Vs. Data TypesInside a classPrimitive VariablesReference VariablesCreating ObjectsChanging the Reference VarGarbage CollectionUsing ObjectsQuestionsThe class Stringname = “Van Helsing”;Slide 17Common String MethodsSlide 19String ExamplesUsing Dialog Boxes for I/OJOptionPane MethodsshowMessageDialogmessageTypeJOptionPane ExampleUsingGUI.java exampleReading From Text FilesSlide 28ExceptionsWriting To Text FilesSlide 31User InputThe StringTokenizer ClassTokens and DelimitersSlide 35Tokenize.java exampleFormatting the Output of Decimal Numbersclass DecimalFormatExamplesTo doCOMP 14Introduction to ProgrammingMiguel A. OtaduyMay 17, 2004Last Friday•Variables and expressions•Input/output•Writing a whole programAny questions?Today•Classes and objects•Graphical user interface (GUI)•File input/output•Formatting input and outputClasses•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 statementsClasses•What is a class?–Data–Operations•Classes allow creation of new data typespublic class Student{}Classes Vs. Data TypesAbstract Descriptors–Data Type–ClassConcrete Entities–Variable–ObjectInside a class•Other classes•Data types•Methods (operations)public class Student{private String name;private int age;public void ComputeGrade();}Primitive Variablesint 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 inReference VariablesInteger 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 locationCreating Objects•We use the new operator to create objects, called instantiation Integer num;num = new Integer(78);parameterChanging the Reference Varnum = new Integer (50);•The address of the newly-created object is stored in the already-created reference variable numGarbage 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!”);objectmethodinformation provided to the method(parameters)Using Objects•System.out object –represents a destination to which we can send output•Example:–println methoddot operatorQuestions1. 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.newdot (.)FalseTrueThe class String•String variables are reference variables•Given String name; –Equivalent Statements:name = new String(“Van Helsing”);name = “Van Helsing”;name = “Van Helsing”;Van HelsingVan HelsingVan HelsingThe 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 operatorCommon 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 strCommon 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 caseString ExamplesString 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());n117van helsingUsing 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•showInputDialogstr = JOptionPane.showInputDialog(strExpression);–stores what the user enters into the String str•showMessageDialogJOptionPane.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 displayedmessageType•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 iconJOptionPane ExampleJOptionPane.showMessageDialog (null,"Hello World!", "Greetings", JOptionPane.INFORMATION_MESSAGE);UsingGUI.java exampleReading 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() methodReading From Text FilesString 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 exceptionpublic static void main (String[] args) throws FileNotFoundException,IOExceptionWriting To Text Files•Similar to reading from text files•Use FileWriter and PrintWriter instead of FileReader and


View Full Document

UNC-Chapel Hill COMP 14 - LECTURE NOTES

Download LECTURE NOTES
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view LECTURE NOTES and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view LECTURE NOTES 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?