Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
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 Output? – ‘0’ (48) … ‘9’ (57) – ‘A’ (65) … ‘Z’ (90) – ‘a’ (97) … ‘z’ (122) 7 55 String • A class in Java API – http://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 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 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); Output? System.out.println(word); 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 <img src="./pic.jpg" /> String s = "<img src=\"./pic.jpg\" />"; 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); Output? inputLine = in.readLine(); System.out.println(inputLine); Janie } Jones catch(IOException ioe) { System.out.println("File not Found"); } 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 Output? String s = "Rock the Casbah"; Rock String t = s.substring(0, 4); System.out.println(t); • How do we know how to use substring? What’s the header? 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); Output? } Straight to Hell public static String getSongName() { return "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*100 + 1); } } • 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"); Output? System.out.println(myGlobalSong); Jimmy Jazz } Spanish Bombs public static void changeSong(String newSong) { myGlobalSong = newSong; } } 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) { Output? 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; } 5 5 Java Objects (Strings) Example public static void main(String[] args) { String a = "Hateful"; String b = "Career Opportunities"; changeStrings(a, b); Output? System.out.println(a); Hateful System.out.println(b); Career Opportunities } 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 How can methods change local variables? • By assigning returned values • Ex, in the String class: Output? Hello Hell – 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);