cse 114 – computer science i strings, i/o, and methods bonneville salt flats, utah

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

Upload: silvester-morrison

Post on 28-Dec-2015

222 views

Category:

Documents


1 download

TRANSCRIPT

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

CSE 114 – Computer Science IStrings, I/O, and Methods

Bonneville Salt Flats, Utah

Page 2: 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?

755

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

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

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

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

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

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

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

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)

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

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

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

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

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

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

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

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

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

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

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

Writing to a text file

• To use java.io.PrintWriter1. open Stream to file

2. write text one line a a time using println(…)

3. close stream when done (i.e. end of file)

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

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

}

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

Reading from a text file

• To use java.io.BufferedReader1. 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)

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

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?

JanieJones

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

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

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

What we’ve learned so far

• Simple program structure

• Declaring and initializing variables

• Performing simple calculations

• String manipulation

• User I/O

• File I/O

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

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?

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

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

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

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?

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

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.

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

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

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

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)

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

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

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

Calling static methods directly examplepublic 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

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

Calling external static methods examplepublic 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()

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

Static Variables

• We can share variables among static methods– global variables

• How?– Declare a static variable outside of all methods

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

Static Variable Examplepublic 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 JazzSpanish Bombs

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

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

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

Java Primitives Examplepublic 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?55

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

Java Objects (Strings) Examplepublic 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?HatefulCareer Opportunities

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

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