Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CSE 114 – Computer Science I Strings, I/O, and Methods Bonneville Salt Flats, Utah."— Presentation transcript:

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

2 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

3 String A class in Java API –http://java.sun.com/javase/6/docs/api/java/lang/String.htmlhttp://java.sun.com/javase/6/docs/api/java/lang/String.html Used for text: String s1 = "Rudie Can't"; String s2 = s1 + " Fail"; System.out.println(s2); Output? Rudie Can’t Fail

4 More about Strings Each character is stored at an index String sentence = "Charlie Don't Surf"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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

5 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

6 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)

7 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

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

9 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: ");

10 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);

11 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

12 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)

13 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"); }

14 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)

15 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

16 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.*;

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

18 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?

19 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

20 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?

21 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.

22 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

23 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)

24 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

25 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

26 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*100 + 1); } What’s the method header for Math.random ? public static double random()

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

28 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

29 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

30 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

31 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

32 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


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

Similar presentations


Ads by Google