You are on page 1of 51

Week 11 String manipulation and File I/O using Eclipse

Trainee The skeleton code String manipulation


public class MTRTrainee {

/* 1. Instance variables for characters and strings */


/* 2. Member methods on characters and strings */ public char whatIsMyGender() { } public String whatIsTheStationName() { } public String sayGreentingWords(int inputHour) { } public void reverseString(String inputString) { } public void splitSentenseIntoWords(String sentense) { } public static void main() { /* 3. The main method to test the MTRTrainee class */ } }
2

Character (char)
A data type which is used to store exactly ONE character
Note: A pair of single quote is used
public class MTRTrainee { /* 1. Instance variables for characters */

private char gender = 'M'; // an example of character


}

Compilation error when more than one characters


A compilation error occurs if we type more than one character inside a pair of single quotes
public class MTRTrainee { /* 1. Instance variables for characters */

// A compilation error occurs if more than one characters // are assigned to a char variable

private char gender = 'Male';


}
4

Escape sequence
Especial sequence is a special case
An extra backslash is added in front of the special character
public class MTRTrainee {

// Examples of escape sequence char tabChar = \t; char nextLineChar = \n; char backSlashChar = \\; char singleQuote = \; char doubleQuote = \;
}
5

String
What happen if the trainee need to record more than ONE character?
Examples: Record his own name, store the name of the MTR station.

Solution #1: An array of character


Example:
char[ ] stationName;

Solution #2: String


String is an abstract data type (ADT) Example:
String stationName;
6

String
String stores a sequence of characters
A string stores characters from index 0 to N-1, where N is the length of the string Use a pair of double quotes
public class MTRTrainee { // An instance variable to store the name private String stationName = "HangHau"; }

Syntax: String nameOfVariable = String message;


7

String Reference Type


In the previous example, the stationName is a reference variable to a string Consider the following example:
public class MTRTrainee { // The variable can be used to reference any string private String stationName ; public MTRTrainn() { stationName = HangHau; stationName = Central; stationName = ChoiHung; } }
8

String operations
String is an Abstract Data Type (ADT) In this course, we will discuss the following methods / operations
length()
Count the length of a string

substring(int i, int j)
A substring with character from index i to j-1

equals(String other)
Compare the current string with another string

charAt(int index)
Returns a character located at the given index

String concatenation using the addition operator (+)

Length of a string
A method length() is used to count the number of characters in a string Example:
String stationName = HangHau; int size = stationName.length();
The value of the variable size will be set to 7 because HangHau has exactly 7 characters

10

PRS (1)
Consider the following programming statements. Which of the followings is the correct choice?
int lenOfStr = Is it possible?.length();
(1) It is a syntax error (2) It is a runtime error (3) lenOfStr will be set to zero (4) lenOfStr will be set to 15
11

Accessing a character in a String


Unlike Array, you cant use the [ ] operator The charAt() method can be used to access a character from a string Example:
String stationName = Central; char firstChar = stationName.charAt(0);
stationName:

C e n t r a l
0 1 2 3 4 5 6
12

Getting a substring
String substring(int i, int j)
A substring includes characters starting from index i to index j-1

Example:
String stationName = Central; String subStr = stationName.substring(2, 5);
stationName

C e n t r a l
0 1 2 3 4 5 6
13

subStr

Equality of two strings


You should use equals() instead of == to compare the equality of two strings Syntax:
boolean equals(String anotherStr)

Example:
if (stationName.equals(Central)) {
// do something if the stationName is Central

}
14

Getting instance variables Char and String


public class MTRTrainee {

private char gender = 'M'; private String stationName = "HangHau";

public char whatIsMyGender() {return gender;} public String whatIsTheStationName() {return stationName;}
public String sayGreentingWords(int inputHour) { } public void reverseString(String inputString) { } public void splitSentenseIntoWords(String sentense) { } }

15

String concatenation
Addition operator (+) on String
public class MTRTrainee { // Previous parts are skipped public String sayGreentingWords(int inputHour) { String prefix = "Good" ; String posfix = ""; if ( inputHour >= 12 && inputHour < 18) posfix = "afternoon!"; else if (inputHour >= 18 && inputHour < 24) posfix = "evening!"; else posfix = "morning! " ;

Greeting words:
If the inputHour is 0..11: Good morning! 12..17: Good afternoon! 18..23: Good evening!

return prefix + " + posfix; // + operator


} // The remaining parts are skipped }
16

Example: Reverse a string


public class MTRTrainee { private char gender = 'M'; private String stationName = "HangHau"; public char whatIsMyGender() {return gender;} public String whatIsTheStationName() {return stationName;} public String sayGreentingWords(int inputHour){/* string concatenation */ }

public void reverseString(String inputString) { /* Print out the reversed String based on the inputString */ }
public void splitSentenseIntoWords(String sentense) { }

17

Reverse a string (Step 1)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

18

Reverse a string (Step 2)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

l
19

Reverse a string (Step 3)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

l a
20

Reverse a string (Step 4)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

l a r
21

Reverse a string (Step 5)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

l a r t
22

Reverse a string (Step 6)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

l a r t n
23

Reverse a string (Step 7)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

l a r t ne
24

Reverse a string (Step 8)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; i>=0; i--) { System.out.print( inputString.charAt(i) ); } inputString:

Cen t r a l
0 1 2 3 4 5 6
Value of the counter i:

System.out.println(); // to the next line


} Console output:

l a r t neC
25

Reverse a string (step 9)


public void reverseString(String inputString) { System.out.print("The reversed string is: "); for (int i=inputString.length()-1; inputString:

Cen t r a l
0 1 2 3 4 5 6

i>=0; i--) {

System.out.print( inputString.charAt(i) ); }

System.out.println(); // to the next line


} Console output:

l a r t neC
26

Advanced example: Split a sentence into words


Given a sentence separated by empty spaces, print words in separated lines
public void splitSentenseIntoWords(String sentence) {

int prevIndex = 0; // The first substring starts at index 0 for ( int i=0; i<=sentence.length(); i++ ) { // If the ith char is an empty space OR // it reaches the end of the sentense if ( i==sentence.length() || sentence.charAt(i) == ' ' ) {
System.out.println( sentense.substring( prevIndex, i )); prevIndex = i+1; // The next substring starts at index i+1 } // end if } // end for

27

The main method of the MTRTrainee class


public static void main(String[] args) {

MTRTrainee john = new MTRTrainee();


// Report the gender System.out.println("Gender is " + john.whatIsMyGender());

// Greeting words at 8am System.out.println("Greeting words: " + john.sayGreentingWords(8)); // Reverse a given string john.reverseString("Hello"); // Split a given string to a list of words john.splitSentenseIntoWords ("Hong Kong University of Science and Technology"); }
28

Array of String
What happen if the manager needs to record the MTR stations in Tseung Kwan O line? (We have 7 stations!)
For simplicity, no spaces are inserted to the names of the stations
NorthPoint YauTong TseungKwanO TiuKengLeng HangHau PoLam

QuarryBay

29

Example: Declare and initialize an array of String


public class MTRManager { private String[] stationNames; // An array of string public MTRManager() { stationNames = new String[7]; // 7 station names stationNames[0] = "NorthPoint"; // 1st station: NorthPoint stationNames[1] = "QuarryBay"; // 2nd station: QuarryBay stationNames[2] = "YauTong"; // 3rd station: YauTong stationNames[3] = "TiuKengLeng"; // 4th station: TiuKengLeng stationNames[4] = "TseungKwanO"; // 5th station: TKO stationNames[5] = "HangHau"; // 6th station: HangHau stationNames[6] = "PoLam"; // The last station: Po Lam /* The remaining parts are skipped */ public static void main(String[] args) { /* The main method to test the MTRManager class*/ }

30

Example: Print the names of the stations


stationNames is an array of String, you should use stationNames.length
stationNames.length() is not allowed A loop is used to print an array of stations
public void printStationNames() { // stationNames is an array, use .length instead of .length() int nStations = stationNames.length; System.out.println("The names of " + nStations + " stations"); for (int i=0; i< nStations; i++) { System.out.println("Station "+ i + ": " + stationNames[i]); }

}
31

Advanced example: Print rightjustified names of the stations


Notice the usage of length and length()
public void printRightJustifiedStationNames() { int nStations = stationNames.length; int maxLen = stationNames[0].length(); for (int i=0; i< nStations; i++) if ( stationNames[i].length() > maxLen ) maxLen = stationNames[i].length(); System.out.println("Right justified stations"); for (int i=0; i< nStations; i++) { int numOfSpaces=maxLen-stationNames[i].length(); for (int j=0; j<numOfSpaces; j++) System.out.print(" "); System.out.println(stationNames[i]); } }

Result:

32

Advanced example: Merge words into a sentence


// Merge array of strings into a single string separated by spaces private String mergeWordsToSentence(String[] words) { String retSentence = ""; // starts from an empty string for (int i=0; i<words.length; i++) { retSentence = retSentence + words[i] + " " ; } return retSentence; // return the whole sentense } // Demonstrate the usage of the above method public void printSentenceFromWords() { String[] words={"Hong","Kong","University","of","Science","and","Technology"}; String sentence = mergeWordsToSentence(words); // invoke the method System.out.println("Sentence: " + sentence); // print it out }
33

File I/O
Three steps of file I/O
1.open/create a file 2.read/write/do something with the file 3.close the file

We are using File/PrintWriter/Scanner classes for this course


These are Javas pre-defined classes, we only need to import the corresponding libraries
34

File I/O (Input/Output)


Why do we need File I/O?
Recall the following part of the flowchart in Lecture 1: Introduction to Computer
Memory
Storage devices

Variables in the memory will vanish if the program is terminated An external file on a storage device persists when the program is terminated
35

Importing libraries
To make use of the pre-defined classes of File I/O in Java, add these lines to the beginning of code:
// The import import import first few lines java.io.File; java.io.PrinterWriter; java.util.Scanner;

// The remaining parts


36

Exception handling
Exception handing is necessary when performing file I/O
E.g. an incorrect filename, error in opening a file

Exception handling is beyond the scope of this course


To workaround with exception handing, you need to add throws Exception next to the method header when you read/write a file public void doSomeFileIO() throws Exception { // some File I/O code }
37

File Output: Using PrintWriter


Steps to use a PrintWriter
1. Create a File object by a given filename 2. Create a PrintWriter object using the File object 3. Invoke print() method several times 4. Invoke close() method to close the file
NorthPoint YauTong TseungKwanO TiuKengLeng HangHau
38

PoLam

QuarryBay

The skeleton code to use PrintWriter


// Write an array of station names to a file named output.txt public void writeStationNamesToFile() throws Exception {

/* 1. Create a file object */


/* 2. Create a PrintWriter object */ /* 3. Invoke print() method several times */ /* 4. Invoke the close() method to save the file */ }

39

Step 1: File object


File object is necessary when you need to create a PrintWriter object
// Write an array of station names to a file named output.txt public void writeStationNamesToFile() throws Exception { // Create a file object by the output filename: output.txt

File outputFile = new File( output.txt );


/* 2. Create a PrintWriter object */ /* 3. Invoke print() method several times */ /* 4. Invoke the close() method to save the file */ }
40

Step 2: PrintWriter object


PrintWriter helps you write content to an external file based on the file object
// Write an array of station names to a file named output.txt public void writeStationNamesToFile() throws Exception { File outputFile = new File( output.txt ); // Create a PrintWriter object based on the File object

PrintWriter writer = new PrintWriter(outputFile);


/* 3. Invoke print() method several times */ /* 4. Invoke the close() method to save the file */ }
41

Step 3: Using print() method in PrintWriter


PrintWriter helps you write content to an external file based on the file object
// Write an array of station names to a file named output.txt public void writeStationNamesToFile() throws Exception { File outputFile = new File( output.txt ); PrintWriter writer = new PrintWriter(outputFile);

// A loop is used to print the array of station names for (int i=0; i< stationNames.length; i++) { writer.print( stationNames[i] ); // print the ith station name if ( i < stationNames.length - 1) // if it is not the last writer.print("\n"); // move to the next line }
/* 4. Invoke the close() method to save the file */ }
42

Step 4: Close the file


To save the file content, you must close the file by invoking the close() method
// Write an array of station names to a file named output.txt public void writeStationNamesToFile() throws Exception { File outputFile = new File( output.txt ); PrintWriter writer = new PrintWriter(outputFile); // A loop is used to print the array of station names for (int i=0; i< stationNames.length; i++) { writer.print( stationNames[i] ); // print the ith station name if ( i < stationNames.length - 1) // if it is not the last writer.print("\n"); // move to the next line }
Result:

writer.close(); // close the file to write the content


}
43

File Input: Using Scanner


Steps to use a Scanner
1. Create a File object by a given filename 2. Create a Scanner object using the File object. 3. The following methods can be used by the Scanner object:
The following slides will go through some useful Turn to next methods defined in Scanner class
Page

4. Close the file by using close() method

44

Useful methods in Scanner class


Read content from a file: Check the availability of
nextLine()
Returns the next line of string

the content from a file:


hasNextLine()
Returns true if the next line exists

next()
Returns the next string (only the first will be returned if the line contains many words)

hasNext()
Returns true if the next string exists

nextInt(), nextDouble()
Reads the next string and try to convert it to an integer (int) / a floating point number (double)

hasNextInt(), hasNextDouble()
Returns true if the next int/double exists

45

http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

Example: Use Scanner to read the names of the stations


public void readStationNamesFromFile() throws Exception { // 1. Create a File and Scanner objects File inputFile = new File("input.txt"); Scanner input = new Scanner(inputFile); // 2. Create an array of strings stationNames = new String[7];

Input.txt:

// 3. read the content using a loop for (int i=0; i<7; i++) { String inputStation = input.nextLine(); stationNames[i] = inputStation; } // 4. close the file and print the result input.close(); printStationNames() ;
}

Result:

46

The main method of the MTRManager class


public static void main(String[] args) throws Exception { MTRManager peter = new MTRManager();

System.out.println("=== Station names ==="); peter.printStationNames();


System.out.println("=== Right-justified station names ==="); peter.printRightJustifiedStationNames(); System.out.println("=== Write stations to output.txt ==="); peter.writeStationNamesToFile(); System.out.println("=== Read stations from input.txt ==="); peter.readStationNamesFromFile(); }
47

Summary
In this week, we have learned
String manipulation File output using PrintWriter File input using Scanner

48

Appendix

49

Converting Strings to Integers


To convert a string into an int value, you can use the static parseInt() method in the Integer class In general, you can find similar methods in Byte, Long classes

50

Converting Strings to floating point values


To convert a string into a double value, you can use the static parseDouble() method in the Double class You can find a similar method in Float class

51