CSE 114 – Computer Science I Strings, I/O, and Methods Bonneville Salt Flats, Utah.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Introduction to Computer Programming Stringing Along – Using Character and String Data.
Fundamental Programming Structures in Java: Strings.
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.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
Hello, world! Dissect HelloWorld.java Compile it Run it.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
© 2007 Lawrenceville Press Slide 1 Chapter 6 The while Statement  Loop structure that executes a set of statements as long as a condition is true  The.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Two Ways to Store Data in a File Text format Binary format.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Recitation 2 Main Method, API & Packages, Java Basics.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
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.
Mt. Rushmore, South Dakota CSE 114 – Computer Science I Static Methods andVariables.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Bryce Canyon, Utah CSE 114 – Computer Science I Objects and Reference.
EXAM 1 REVIEW. days until the AP Computer Science test.
Chapter 2: Java Fundamentals
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
OOP (pre) Basic Programming. Writing to Screen print will display the string to the screen, the following print statement will be appended to the previous.
Introduction to Java Java Translation Program Structure
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
By Mr. Muhammad Pervez Akhtar
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Computer Programming with Java Chapter 2 Primitive Types, Assignment, and Expressions.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
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,
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
Introduction to programming in java
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Chapter 2 Clarifications
Strings, StringBuilder, and Character
String class.
Introduction to Computer Science / Procedural – 67130
Strings and File I/O.
String Handling in JAVA
Java Programming: From Problem Analysis to Program Design, 4e
Primitive Types Vs. Reference Types, Strings, Enumerations
Modern Programming Tools And Techniques-I Lecture 11: String Handling
MSIS 655 Advanced Business Applications Programming
An Introduction to Java – Part I, language basics
Chapter 2: Basic Elements of Java
Chapter 3 Spring 2006 CS 101 Aaron Bloomfield
Using Objects (continued)
CS2011 Introduction to Programming I Strings
Presentation transcript:

CSE 114 – Computer Science I Strings, I/O, and Methods Bonneville Salt Flats, Utah

Java character data char Type for a single character Each char is a 2-byte number (Unicode) char symbol = '7'; System.out.println(symbol); System.out.println((int)symbol); Unicode character set –‘0’ (48) … ‘9’ (57) –‘A’ (65) … ‘Z’ (90) –‘a’ (97) … ‘z’ (122) Output? 7 55

String A class in Java API – Used for text: String s1 = "Rudie Can't"; String s2 = s1 + " Fail"; System.out.println(s2); Output? Rudie Can’t Fail

More about Strings Each character is stored at an index String sentence = "Charlie Don't Surf"; C h a r l i e D o n ' t S u r f The String class (from J2SE) has methods to process strings. System.out.println("charAt(6) is " + sentence.charAt(6)); System.out.println(sentence.toUpperCase()); System.out.println(sentence); System.out.println(sentence.substring(0,7) + sentence.substring(14)); charAt(6) is e CHARLIE DON'T SURF Charlie Don't Surf CharlieSurf Output to Console window by println methods

Strings are immutable! There are no methods to change them once they have been created So how can I change a String? 1.make a new one 2.assign the new one to the old variable String word = "Hello"; word.substring(0,4); System.out.println(word); word = word.substring(0, 4); System.out.println(word); Output? Hello Hell

String functions “+” used for building new Strings. Ex: String s = "If Music "; s = s + "Could Talk"; int mins = 4, secs = 36; String t = s + " (" + mins + ":" + secs + ")"; System.out.println(t); Output? If Music Could Talk (4:36)

Useful String functions charAt equals equalsIgnoreCase compareTo startsWith endsWith indexOf lastIndexOf replace substring toLowerCase toUpperCase trim s.equals(t) returns true if s and t have same letters false otherwise

Special Characters '\n' – newline '\t' – tab '\"' – quotation mark Ex, how can we print String s = " "; System.out.println(s);

How can we get user input? API methods One option: from console window Scanner input = new Scanner(System.in); System.out.print("Enter text: "); String text = input.nextLine(); Another option: use a dialog text = JOptionPane.showInputDialog("Enter text: ");

How do we provide output? API methods One option: to console window (duh) int num = 5; System.out.print("Print five: " + num); Another option: use a dialog int num = 5; String text = "Print five: " + num; JOptionPane.showMessageDialog(null, text);

How about reading/writing from/to a file? We use objects called streams Java as different types of streams –text –object –byte –etc. Let’s see how to use a text stream –in Java, use BufferedReader/PrintWriter

Writing to a text file To use java.io.PrintWriter 1.open Stream to file 2.write text one line a a time using println(…) 3.close stream when done (i.e. end of file)

Text File Writing Example try { File file = new File("Output.txt"); Writer writer = new FileWriter(file); PrintWriter out = new PrintWriter(writer); out.println("Janie"); out.println("Jones"); out.close(); } catch(IOException ioe) { System.out.println("File not Found"); }

Reading from a text file To use java.io.BufferedReader 1.open Stream to file 2.read text one line a time using readLine() readLine returns null if no more text to read 3.close stream when done (i.e. end of file)

Text File Reading Example try { File file = new File("Output.txt"); Reader reader = new FileReader(file); BufferedReader in = new BufferedReader(reader); String inputLine = in.readLine(); System.out.println(inputLine); inputLine = in.readLine(); System.out.println(inputLine); } catch(IOException ioe) { System.out.println("File not Found"); } Output? Janie Jones

Import statements Makes existing classes available to your program What classes? –API classes Put at top of file using the class Ex: // MAKE Scanner AVAILABLE import java.util.Scanner; // Make all java.io classes available import java.io.*;

What we’ve learned so far Simple program structure Declaring and initializing variables Performing simple calculations String manipulation User I/O File I/O

import java.util.Scanner; public class ChangeMaker { public static void main(String[] args) { int change, rem, qs, ds, ns, ps; System.out.print("Input change amount (1-99): "); Scanner input = new Scanner(System.in); change = input.nextInt(); qs = change / 25; rem = change % 25; ds = rem / 10; rem = rem % 10; ns = rem / 5; rem = rem % 5; ps = rem; System.out.println(qs + " quarters"); System.out.println(ds + " dimes"); System.out.println(ns + " nickels"); System.out.println(ps + " pennies"); } // main } // class ChangeMaker Remember our program?

What will we add next? Decision making –if - else statements Relational Operators Logical Operators –switch statements Iteration – efficient way of coding repetitive tasks –do … while statements –while statements –for statements

But First! Can you name a method we’ve used so far? What is a method? Can we define our own methods? Why should we write methods? What’s the point?

Why write methods? To shorten your programs –avoid writing identical code twice or more To modularize your programs –fully tested methods can be trusted To make your programs more: –readable –reusable –testable –debuggable –extensible –adaptable –etc.

Rule of Thumb If you have to perform some operation in more than one place inside your program, make a new method to implement this operation and have other parts of the program use it Ex: printing to the console

Method Header Describes how to use a method. Includes: –return type –name of method –method arguments Note: documentation should describe method behavior String s = "Rock the Casbah"; String t = s.substring(0, 4); System.out.println(t); How do we know how to use substring? What’s the header? Output? Rock public String substring(int beginIndex, int endIndex)

Static methods Remember the main method header? public static void main(String[] args) What does static mean? –associates a method with a particular class name –any method can call a static method either: directly from within same class OR using class name from outside class

Calling static methods directly example public class StaticCallerWithin { public static void main(String[] args) { String song = getSongName(); System.out.println(song); } public static String getSongName() { return "Straight to Hell"; } Output? Straight to Hell

Calling external static methods example public class StaticCallerFromOutside { public static void main(String[] args) { System.out.print("Random Number from 1-100: "); double randomNum = Math.random(); System.out.print(randomNum* ); } What’s the method header for Math.random ? public static double random()

Static Variables We can share variables among static methods –global variables How? –Declare a static variable outside of all methods

Static Variable Example public class MyProgram { static String myGlobalSong = "Jimmy Jazz"; public static void main(String[] args) { System.out.println(myGlobalSong); changeSong("Spanish Bombs"); System.out.println(myGlobalSong); } public static void changeSong(String newSong) { myGlobalSong = newSong; } Output? Jimmy Jazz Spanish Bombs

Call-by-value Note: –method arguments are copies of the original data Consequence? –methods cannot assign (‘=’) new values to arguments and affect the original passed variables Why? –changing argument values changes the copy, not the original

Java Primitives Example public static void main(String[] args) { int a = 5; int b = 5; changeNums(a, b); System.out.println(a); System.out.println(b); } public static void changeNums(int x, int y) { x = 0; y = 0; } Output? 5 5

Java Objects (Strings) Example public static void main(String[] args) { String a = "Hateful"; String b = "Career Opportunities"; changeStrings(a, b); System.out.println(a); System.out.println(b); } public static void changeString(String x, String y) { x = "The Magnificent Seven"; y = "The Magnificent Seven"; } NOTE: When you pass an object to a method, you are passing a copy of the object’s address Output? Hateful Career Opportunities

How can methods change local variables? By assigning returned values Ex, in the String class: –substring method returns a new String String s = "Hello"; s.substring(0, 4); System.out.println(s); s = s.substring(0, 4); System.out.println(s); Output? Hello Hell