Carron Shankland. Content. String manipula3on in Java The use of files in Java The use of the command line arguments References:



Similar documents
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

JAVA.UTIL.SCANNER CLASS

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Object-Oriented Programming in Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

D06 PROGRAMMING with JAVA

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Chapter 2: Elements of Java

Introduction to Programming

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Using Files as Input/Output in Java 5.0 Applications

13 File Output and Input

Introduction to Java

Install Java Development Kit (JDK) 1.8

Chapter 3. Input and output. 3.1 The System class

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

AP Computer Science Static Methods, Strings, User Input

6.1. Example: A Tip Calculator 6-1

Comp 248 Introduction to Programming

Computer Programming I

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Building Java Programs

Introduction to Java. CS 3: Computer Programming in Java

J a v a Quiz (Unit 3, Test 0 Practice)

Lecture 5: Java Fundamentals III

CS 106 Introduction to Computer Science I

Week 1: Review of Java Programming Basics

Chapter 2 Elementary Programming

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Some Scanner Class Methods

CS106A, Stanford Handout #38. Strings and Chars

Building Java Programs

AP Computer Science File Input with Scanner

java Features Version April 19, 2013 by Thorsten Kracht

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Chapter 2 Introduction to Java programming

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Variables, Constants, and Data Types

Visit us at

CS 106 Introduction to Computer Science I

Event-Driven Programming

Unit 6. Loop statements

Programming Languages CIS 443

Quick Introduction to Java

Building a Multi-Threaded Web Server

AP Computer Science Java Subset

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

Pemrograman Dasar. Basic Elements Of Java

Sample CSE8A midterm Multiple Choice (circle one)

Basics of Java Programming Input and the Scanner class

Course Intro Instructor Intro Java Intro, Continued

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Programmierpraktikum

Topic 11 Scanner object, conditional execution

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Basic Programming and PC Skills: Basic Programming and PC Skills:

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Reading Input From A File

Programming and Data Structures with Java and JUnit. Rick Mercer

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Introduction to Java Lecture Notes. Ryan Dougherty

Chapter 2 Basics of Scanning and Conventional Programming in Java

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Java Application Developer Certificate Program Competencies

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

LOOPS CHAPTER CHAPTER GOALS

10 Java API, Exceptions, and Collections

Programming in Java. What is in This Chapter? Chapter 1

Crash Course in Java

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Files and input/output streams

Java Programming Fundamentals

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

AP Computer Science Java Mr. Clausen Program 9A, 9B

Using Two-Dimensional Arrays

Java Basics: Data Types, Variables, and Loops

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Building Java Programs

Arrays. Introduction. Chapter 7

Chapter 8. Living with Java. 8.1 Standard Output

D06 PROGRAMMING with JAVA

public static void main(string[] args) { System.out.println("hello, world"); } }

Part I. Multiple Choice Questions (2 points each):

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Hypercosm. Studio.

Building Java Programs

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Introduction to Python

Explain the relationship between a class and an object. Which is general and which is specific?

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Transcription:

CSCU9T4 (Managing Informa3on): Strings and Files in Java Carron Shankland Content String manipula3on in Java The use of files in Java The use of the command line arguments References: Java For Everyone, 2 nd Edi3on (2013), by Cay Horstmann Chapter 02: sec3on 2.3 and 2.5 (strings) Chapter 07: sec3ons 7.1, 7.2, 7.3 (files) The lecture material comes from this book M. T. Goodrich and R. Tamassia, Data Structures and Algorithms in Java, 5th edi3on Character strings (such as those displayed in the board) are important data types in any Java program. We will learn how to work with text, and how to perform useful tasks with them. We will also learn how to write programs that manipulate text files, a very useful skill for processing real world data. 2

String Processing facili3es in Java A common method to manipulate strings in Java is to use the the String class (you can also use StringBuffer) The String class provides a lot of useful methods, including those for crea3ng and manipula3ng strings inspec3ng the characters in a string splixng up a string into tokens We will take a quick tour of some of the most useful of these (azer a quick recap of the features you know already) substring, trim, split touppercase, tolowercase equals, endswith, startswith charat, indexof, lastindexof We will also look at the StringTokenizer class TIP: Refer to Java docs! h\p://www.cs.s3r.ac.uk/doc/java/jdk1.6/ University of S3rling Strings Many programs process text, not numbers Text consists of characters: le\ers, numbers, punctua3ons, spaces, etc. What is a string? An ordered collec3on of characters of arbitrary length Consider S3rling, You rock!, 67.435, 3.8x104, or 5.2e6? In our world strings delineated by quota3ons: University of S3rling 4

Common uses of strings Input from a user, or from a (data) file the program must understand what the string represents making sense of a string (determining its syntax) is called parsing e.g. a Url Output maybe on the screen, or to a file Strings are ozen converted to/from other formats, e.g. string/number conversions are very common, including integers, floa3ng point numbers can also have general string/object conversions As programmers, we need to be able to process strings University of S3rling Examples of string processing A compiler takes the text of a program as input, and its first task is to parse the input A word processor looks to see which are the individual words of a line of text so that it can spell check them. A browser must parse a URL into pieces: which protocol to use which web server to contact which file to ask for from that web server University of S3rling

2.5 Strings q The String Type: Type Variable Literal String name = Harry q Once you have a String variable, you can use methods such as: int n = name.length(); // n will be assigned 5 q A String s length is the number of characters inside: An empty String (length 0) is shown as The maximum length is quite large (an int) Copyright 2013 by John Wiley & Sons. Page 7 String concatena3on Java: + operator is used to concatenate strings. Put them together to produce a longer string. Example: String fname = Harry, String lname = Morgan String name = fname + lname Results in the string: HarryNorman If you d like the first and last name separated by a space: String name = fname + + lname Results in the string: Harry Norman When the expression to the lez or right of a + operator is a string, the other one is automa3cally forced to be a string, and both strings are concatenated. Example: String jobtitle = Agent, int empid = 7 String bond = jobtitle + empid Results in the string: Agent7 University of S3rling 8

2.3 Input and Output Reading Input You might need to ask for input (aka prompt for input) and then save what was entered. We will be reading input from the keyboard For now, don t worry about the details This is a three step process in Java 1) Import the Scanner class from its package java.util import java.util.scanner; 2) Setup an object of the Scanner class Scanner in = new Scanner(System.in); 3) Use methods of the new Scanner object to get input int bottles = in.nextint(); double price = in.nextdouble(); Page 9 Syntax 2.3: Input Statement The Scanner class allows you to read keyboard input from the user It is part of the Java API util package Java classes are grouped into packages. Use the import statement to use classes from packages. Page 10

String Input q You can read a String from the console with: System.out.print("Please enter your name: "); String name = in.next(); The next method reads one word at a time It looks for white space delimiters q You can read an entire line from the console with: System.out.print("Please enter your address: "); String address = in.nextline(); The nextline method reads until the user hits Enter q Converting a String variable to a number System.out.print("Please enter your age: "); String input = in.nextline(); int age = Integer.parseInt(input); // only digits! Copyright 2013 by John Wiley & Sons. Page 11 String Escape Sequences q How would you print a double quote? Preface the " with a \ inside the double quoted String System.out.print("He said \"Hello\""); q OK, then how do you print a backslash? Preface the \ with another \! System.out.print(" C:\\Temp\\Secret.txt ); q Special characters inside Strings Output a newline with a \n System.out.print("*\n**\n***\n"); * ** *** Copyright 2013 by John Wiley & Sons. Page 12

Strings and Characters q Strings are sequences of characters Unicode characters to be exact Characters have their own type: char Characters have numeric values See the ASCII code chart in Appendix B For example, the letter H has a value of 72 if it were a number q Use single quotes around a char char initial = B ; q Use double quotes around a String String initials = BRL ; Copyright 2013 by John Wiley & Sons. Page 13 Copying a char from a String q Each char inside a String has an index number: 0 1 2 3 4 5 6 7 8 9 c h a r s h e r e q The first char is index zero (0) q The charat method returns a char at a given index inside a String: String greeting = "Harry"; char start = greeting.charat(0); char last = greeting.charat(4); 0 1 2 3 4 H a r r y Copyright 2013 by John Wiley & Sons. Page 14

Copying portion of a String q A substring is a portion of a String q The substring method returns a portion of a String at a given index for a number of chars, starting at an index: 0 1 String greeting = "Hello!"; String sub = greeting.substring(0, 2); H e 0 1 2 3 4 5 H e l l o! String sub2 = greeting.substring(3, 5); Page 15 Example: initials.java 1 import java.util.scanner; 2 3 /** 4 This program prints a pair of initials. 5 */ 6 public class Initials 7 { 8 public static void main(string[] args) 9 { 10 Scanner in = new Scanner(System.in); 11 12 // Get the names of the couple 13 14 System.out.print("Enter your first name: "); 15 String first = in.next(); 16 System.out.print("Enter your significant other's first name: "); 17 String second = in.next(); 18 19 // Compute and display the inscription 20 21 String initials = first.substring(0, 1) 22 + "&" + second.substring(0, 1); 23 System.out.println(initials); 24 } 25 } Page 16 Copyright 2013 by John Wiley & Sons.

The StringTokenizer Class The StringTokenizer class allows a string to be split into pieces know as tokens A delimiter character is specified, and this is used to break down the original string into tokens. We start a new token every 3me a delimiter character is detected. For example, with the string "http://www.cs.stir.ac.uk/courses/csc9v4/" and the delimiter '/', the individual tokens in that string would be "http:", "www.cs.stir.ac.uk", "courses", and "CSC9V4". More usually, with the default space character delimiter, a line of text can be broken up into individual words. This is how a word processor works out where words begin and end. University of S3rling StringTokenizer Example 1 StringTokenizer st; // Declare a reference st = new StringTokenizer("this is a test"); while (st.hasmoretokens()) { System.out.println(st.nextToken()); } The above program produces: this is a test University of S3rling

StringTokenizer Example 2 String input="http://www.cs.stir.ac.uk/index.htm";! String delims= "/";!! StringTokenizer st;!// Declare a reference! st = new StringTokenizer(input,delims);!! while (st.hasmoretokens())! System.out.println(st.nextToken()); The above program produces: http: www.cs.stir.ac.uk index.htm University of S3rling The String.split method In Java 1.5, a new method of tokenizing strings was introduced. An addi3onal method called split was added to the String class. The API guide for split is: public String[] split(string regex) where regex is a regular expression or pa\ern used to determine how to break up the String. For example we could just use the forward slash delimiter as before /, alterna3vely we can use \\s+ which means one or more white spaces, or two\\s + which looks for the word two followed by one or more white spaces. (What are \\d, \\D, \\w, \\W?) Regular expressions are very powerful selectors split returns an array of tokens; each token is just a String h\p://ocpsoz.org/opensource/guide-to-regular-expressions-in-java-part-1/ University of S3rling

Example: String.split String input="http://www.cs.stir.ac.uk/index.htm";! String delims="/";!! String [] tokens = input.split(delims);!! for (int t=0; t<tokens.length; t++)! System.out.println(tokens[t]); The above code produces: http: 12 // Get the names of the couple www.cs.stir.ac.uk 13 14 System.out.print("Enter your first name: "); 15 String first = in.next(); 16 System.out.print("Enter your significant other's first name: "); 17 String second = in.next(); 18 19 // Compute and display the inscription University 20 of S3rling index.htm 21 String initials = first.substring(0, 1) 22 + "&" + second.substring(0, 1); 23 System.out.println(initials); 24 } 25 } Program Run Enter your first name: Rodolfo Enter your significant other's first name: Sally R&S Table 9: String Operations (1) 2.5 Strings 63 Table 9 String Operations Statement Result Comment string str = "Ja"; str = str + "va"; System.out.println("Please" + " enter your name: "); str is set to "Java" Prints Please enter your name: When applied to strings, + denotes concatenation. Use concatenation to break up strings that don t fit into one line. team = 49 + "ers" team is set to "49ers" Because "ers" is a string, 49 is converted to a string. String first = in.next(); String last = in.next(); (User input: Harry Morgan) String greeting = "H & S"; int n = greeting.length(); String str = "Sally"; char ch = str.charat(1); String str = "Sally"; String str2 = str.substring(1, 4); Copyright 2013 by John Wiley & Sons. String str = "Sally"; String str2 = str.substring(1); first contains "Harry" last contains "Morgan" n is set to 5 ch is set to 'a' str2 is set to "all" str2 is set to "ally" The next method places the next word into the string variable. Each space counts as one character. This is a char value, not a String. Note that the initial position is 0. Extracts the substring starting at position 1 and ending before position 4. Page 22 If you omit the end position, all characters from the position until the end of the string are included. String str = "Sally"; str2 is set to "a" Extracts a String of length

Table 9: String Operations (2) Copyright 2013 by John Wiley & Sons. Page 23 Formatted Output q Outputting floating point values can look strange: Price per liter: 1.21997 q To control the output appearance of numeric variables, use formatted output tools such as: System.out.printf( %.2f, price); Price per liter: 1.22 System.out.printf( %10.2f, price); Price per liter: 1.22 10 spaces 2 spaces The %10.2f is called a format specifier Page 24

Format Types q Formatting is handy to align columns of output q You can also include text inside the quotes: System.out.printf( Price per liter: %10.2f, price); Page 25 Summary: Strings q Strings are sequences of characters. q The length method yields the number of characters in a String. q Use the + operator to concatenate Strings; that is, to put them together to yield a longer String. q Use the next (one word) or nextline (entire line) methods of the Scanner class to read a String. q Whenever one of the arguments of the + operator is a String, the other argument is converted to a String. q If a String contains the digits of a number, you use the Integer.parseInt or Double.parseDouble method to obtain the number value. q String index numbers are counted starting with 0. q Use the substring method to extract a part of a String Copyright 2013 by John Wiley & Sons. Page 26

Files 7.1 Reading and Writing Text Files q Text Files are very commonly used to store information Both numbers and words can be stored as text They are the most portable types of data files q The Scanner class can be used to read text files We have used it to read from the keyboard Reading from a file requires using the File class q The PrintWriter class will be used to write text files Using familiar print, println and printf tools Copyright 2013 by John Wiley & Sons. All rights reserved. Page 28

Text File Input q Create an object of the File class Pass it the name of the file to read in quotes File inputfile = new File("input.txt"); q Then create an object of the Scanner class Pass the constructor the new File object Scanner in = new Scanner(inputFile); q Then use Scanner methods such as: next() nextline() hasnextline() hasnext() nextdouble() nextint()... while (in.hasnextline()) { String line = in.nextline(); // Process line; } Copyright 2013 by John Wiley & Sons. All rights reserved. Page 29 Text File Output q Create an object of the PrintWriter class Pass it the name of the file to write in quotes PrintWriter out = new PrintWriter("output.txt"); If output.txt exists, it will be emptied If output.txt does not exist, it will create an empty file PrintWriter is an enhanced version of PrintStream System.out is a PrintStream object! System.out.println( Hello World! ); q Then use PrintWriter methods such as: print() println() printf() out.println("hello, World!"); out.printf("total: %8.2f\n", totalprice); Copyright 2013 by John Wiley & Sons. All rights reserved. Page 30

Closing Files q You must use the close method before file reading and writing is complete q Closing a Scanner while (in.hasnextline()) { String line = in.nextline(); // Process line; } in.close(); q Closing a PrintWriter Your text may not be saved to the file until you use the close method! out.println("hello, World!"); out.printf("total: %8.2f\n", totalprice); out.close(); Copyright 2013 by John Wiley & Sons. All rights reserved. Page 31 Exceptions Preview q One additional issue that we need to tackle: If the input file for a Scanner doesn t exist, a FileNotFoundException occurs when the Scanner object is constructed. The PrintWriter constructor can generate this exception if it cannot open the file for writing. If the name is illegal or the user does not have the authority to create a file in the given location Copyright 2013 by John Wiley & Sons. All rights reserved. Page 32

Exceptions Preview Add two words to any method that uses File I/O public static void main(string[] args) throws FileNotFoundException Until you learn how to handle exceptions yourself Copyright 2011 by John Wiley & Sons. All rights reserved. Page 33 And an important import or two.. q Exception classes are part of the java.io package Place the import directives at the beginning of the source file that will be using File I/O and exceptions import java.io.file; import java.io.filenotfoundexception; import java.io.printwriter; import java.util.scanner; public class LineNumberer { public void openfile() throws FileNotFoundException {... } } Copyright 2013 by John Wiley & Sons. All rights reserved. Page 34

Example: Total.java (1) More import statements required! Some examples may use import java.io.*; Note the throws clause Copyright 2013 by John Wiley & Sons. All rights reserved. Page 35 Example: Total.java (2) Don t forget to close the files before your program ends. Copyright 2013 by John Wiley & Sons. All rights reserved. Page 36

Common Error 7.1 q Backslashes in File Names When using a String literal for a file name with path information, you need to supply each backslash twice: File inputfile = new File("c:\\homework\\input.dat"); A single backslash inside a quoted string is the escape character, which means the next character is interpreted differently (for example, \n for a newline character) When a user supplies a filename into a program, the user should not type the backslash twice Copyright 2013 by John Wiley & Sons. All rights reserved. Page 37 Common Error 7.2 q Constructing a Scanner with a String When you construct a PrintWriter with a String, it writes to a file: This does not work for a Scanner object It does not open a file. Instead, it simply reads through the String that you passed ( input.txt ) To read from a file, pass Scanner a File object: or PrintWriter out = new PrintWriter("output.txt"); Scanner in = new Scanner("input.txt"); // Error? Scanner in = new Scanner(new File ( input.txt ) ); File myfile = new File("input.txt"); Scanner in = new Scanner(myFile); Copyright 2013 by John Wiley & Sons. All rights reserved. Page 38

7.2 Text Input and Output q In the following sections, you will learn how to process text with complex contents, and you will learn how to cope with challenges that often occur with real data. q Reading Words Example: Mary had a little lamb input while (in.hasnext()) { String input = in.next(); System.out.println(input); } output Mary had a little lamb Copyright 2013 by John Wiley & Sons. All rights reserved. Page 39 Processing Text Input q There are times when you want to read input by: Each Word Each Line One Number One Character Processing input is required for almost all types of programs that interact with the user. q Java provides methods of the Scanner and String classes to handle each situation It does take some practice to mix them though! Copyright 2013 by John Wiley & Sons. All rights reserved. Page 40

q q Reading Words In the examples so far, we have read text one line at a time To read each word one at a time in a loop, use: The Scanner object s hasnext()method to test if there is another word The Scanner object s next() method to read one word while (in.hasnext()) { String input = in.next(); System.out.println(input); } Input: Output: Mary had a little lamb Mary had a little lamb Copyright 2013 by John Wiley & Sons. All rights reserved. Page 41 White Space q The Scanner s next() method has to decide where a word starts and ends. q It uses simple rules: It consumes all white space before the first character It then reads characters until the first white space character is found or the end of the input is reached Copyright 2013 by John Wiley & Sons. All rights reserved. Page 42

White Space q What is whitespace? Characters used to separate: Words Lines Common White Space Space \n NewLine Mary had a little lamb,\n her fleece was white as\tsnow \r Carriage Return \t Tab \f Form Feed Copyright 2013 by John Wiley & Sons. All rights reserved. Page 43 The usedelimiter Method q The Scanner class has a method to change the default set of delimiters used to separate words. The usedelimiter method takes a String that lists all of the characters you want to use as delimiters: Scanner in = new Scanner(...); in.usedelimiter("[^a-za-z]+"); Copyright 2013 by John Wiley & Sons. All rights reserved. Page 44

The usedelimiter Method Scanner in = new Scanner(...); in.usedelimiter("[^a-za-z]+"); You can also pass a String in regular expression format inside the String parameter as in the example above. [^A-Za-z]+ says that all characters that ^not either A- Z uppercase letters A through Z or a-z lowercase a through z are delimiters. Search the Internet to learn more about regular expressions. Copyright 2013 by John Wiley & Sons. All rights reserved. Page 45 Summary: Input/Output q Use the Scanner class for reading text files. q When writing text files, use the PrintWriter class and the print/println/printf methods. q Close all files when you are done processing them. Copyright 2013 by John Wiley & Sons. All rights reserved. Page 46

Summary: Processing Text Files q The next method reads a string that is delimited by white space. q nextdouble (and nextint ) read double, Integer, respectively. Should be used with hasnextdouble and hasnextint respectively to avoid exceptions They do not consume white space following a number q Next lecture How to read complete lines with mixed input (data record) How to read one character at a time Command line arguments Copyright 2013 by John Wiley & Sons. All rights reserved. Page 47 Reading Characters q There are no hasnextchar() or nextchar() methods of the Scanner class Instead, you can set the Scanner to use an empty delimiter ("") Scanner in = new Scanner(...); in.usedelimiter(""); while (in.hasnext()) { char ch = in.next().charat(0); // Process each character } next returns a one character String Use charat(0) to extract the character from the String at index 0 to a char variable Copyright 2013 by John Wiley & Sons. All rights reserved. Page 48

Classifying Characters q The Character class provides several useful methods to classify a character: Pass them a char and they return a boolean if ( Character.isDigit(ch) ) Copyright 2013 by John Wiley & Sons. All rights reserved. Page 49 q q Reading Lines Some text files are used as simple databases Each line has a set of related pieces of information This example is complicated by: Some countries use two words United States It would be better to read the entire line and process it using powerful String class methods while (in.hasnextline()) { String line = in.nextline(); // Process each line } China 1330044605 India 1147995898 United States 303824646 nextline() reads one line and consumes the ending \n Copyright 2013 by John Wiley & Sons. All rights reserved. Page 50

Breaking Up Each Line q Now we need to break up the line into two parts Everything before the first digit is part of the country Get the index of the first digit with Character.isdigit int i = 0; while (!Character.isDigit(line.charAt(i))) { i++; } Copyright 2013 by John Wiley & Sons. All rights reserved. Page 51 Breaking Up Each Line Use String methods to extract the two parts United States String countryname = line.substring(0, i); String population = line.substring(i); 303824646 // remove the trailing space in countryname countryname = countryname.trim(); trim removes white space at the beginning and the end. Copyright 2013 by John Wiley & Sons. All rights reserved. Page 52

Or Use Scanner Methods q Instead of String methods, you can sometimes use Scanner methods to do the same tasks Read the line into a String variable Pass the String variable to a new Scanner object Use Scanner hasnextint to find the numbers If not numbers, use next and concatenate words United States 303824646 Scanner linescanner = new Scanner(line); Remember the next method String countryname = linescanner.next(); consumes white while (!linescanner.hasnextint()) space. { countryname = countryname + " " + linescanner.next(); } Copyright 2013 by John Wiley & Sons. All rights reserved. Page 53 Converting Strings to Numbers q Strings can contain digits, not numbers They must be converted to numeric types Wrapper classes provide a parseint method 3 0 3 8 2 4 6 4 6 String pop = 303824646 ; int populationvalue = Integer.parseInt(pop); String pricestring = 3.95 ; int price = Double.parseInt(priceString); 3. 9 5 Copyright 2013 by John Wiley & Sons. All rights reserved. Page 54

Converting Strings to Numbers q Caution: The argument must be a string containing only digits without any additional characters. Not even spaces are allowed! So Use the trim method before parsing! int populationvalue = Integer.parseInt(pop.trim()); Copyright 2013 by John Wiley & Sons. All rights reserved. Page 55 Safely Reading Numbers q Scanner nextint and nextdouble can get confused If the number is not properly formatted, an Input Mismatch Exception occurs Use the hasnextint and hasnextdouble methods to test your input first if (in.hasnextint()) { int value = in.nextint(); // safe } q They will return true if digits are present If true, nextint and nextdouble will return a value If not true, they would throw an input mismatch exception Copyright 2013 by John Wiley & Sons. All rights reserved. Page 56

Reading Other Number Types q The Scanner class has methods to test and read almost all of the primitive types Data Type Test Method Read Method byte hasnextbyte nextbyte short hasnextshort nextshort int hasnextint nextint long hasnextlong nextlong float hasnextfloat nextfloat double hasnextdouble nextdouble boolean hasnextboolean nextboolean q What is missing? Right, no char methods! Copyright 2013 by John Wiley & Sons. All rights reserved. Page 57 Mixing Number, Word and Line Input q nextdouble (and nextint ) do not consume white space following a number This can be an issue when calling nextline after reading a number China 1330044605 India There is a newline at the end of each line After reading 1330044605 with nextint nextline will read until the \n (an empty String) while (in.hasnextint()) { String countryname = in.nextline(); int population = in.nextint(); in.nextline(); // Consume the newline } Copyright 2013 by John Wiley & Sons. All rights reserved. Page 58

Formatting Output q Advanced System.out.printf Can align strings and numbers Can set the field width for each Can left align (default is right) q Two format specifiers example: System.out.printf("%-10s%10.2f", items[i] + ":", prices[i]); %-10s : Left justified String, width 10 %10.2f : Right justified, 2 decimal places, width 10 Copyright 2013 by John Wiley & Sons. All rights reserved. Page 59 printf Format Specifier q A format specifier has the following structure: The first character is a % Next, there are optional flags that modify the format, such as - to indicate left alignment. See Table 2 for the most common format flags Next is the field width, the total number of characters in the field (including the spaces used for padding), followed by an optional precision for floating-point numbers q The format specifier ends with the format type, such as f for floating-point values or s for strings. See Table 3 for the most important formats Copyright 2013 by John Wiley & Sons. All rights reserved. Page 60

printf Format Flags Copyright 2013 by John Wiley & Sons. All rights reserved. Page 61 printf Format Types Copyright 2013 by John Wiley & Sons. All rights reserved. Page 62

7.3 Command Line Arguments q Text based programs can be parameterized by using command line arguments Filename and options are often typed after the program name at a command prompt: >java ProgramClass -v input.dat public static void main(string[] args) Java provides access to them as an array of Strings parameter to the main method named args args[0]: "-v" args[1]: "input.dat" The args.length variable holds the number of args Options (switches) traditionally begin with a dash - Copyright 2013 by John Wiley & Sons. All rights reserved. Page 63 Caesar Cipher Example q Write a program that encrypts a file scrambles it so it is unreadable except to those who know the encryption method q Use a method familiar to the emperor Julius Caesar (ignoring 2,000 years of progress in encryption) q Replacing A D, B E, C F (shift of a fixed length) Copyright 2014 University of Stirling

arguments: An optional -d flag to indicate decryption instead of encryption The input file name The output file name Caesar Cipher Example q Write a command line program that uses character replacement (Caesar cipher) to: For example, java CaesarCipher input.txt encrypt.txt 1) Encrypt a file provided input and output file names encrypts the file input.txt and places the result into encrypt.txt. >java CaesarCipher input.txt encrypt.txt 2) Decrypt a file as an option java CaesarCipher -d encrypt.txt output.txt decrypts the file >java encrypt.txt CaesarCipher and places d encrypt.txt the result into output.txt. The emperor Julius Caesar used a simple scheme to encrypt messages. Plain text M e e t m e a t t h e Encrypted text P h h w p h d w w k h Figure 1 Caesar Cipher section_3/caesarcipher.java Copyright 2013 by John Wiley & Sons. All rights reserved. Page 65 1 import java.io.file; 2 import java.io.filenotfoundexception; 3 import java.io.printwriter; 4 import java.util.scanner; CaesarCipher.java (1) This method uses file I/O and can throw this exception. Copyright 2013 by John Wiley & Sons. All rights reserved. Page 66

CaesarCipher.java (2) If the switch is present, it is the first argument Call the usage method to print helpful instructions Copyright 2013 by John Wiley & Sons. All rights reserved. Page 67 CaesarCipher.java (3) Process the input file one character at a time Don t forget the close the files! Example of a usage method Copyright 2013 by John Wiley & Sons. All rights reserved. Page 68

Steps to Processing Text Files 1) Understand the Processing Task -- Process on the go or store data and then process? 2) Determine input and output files 3) Choose how you will get file names 4) Choose line, word or character based input processing -- If all data is on one line, normally use line input 5) With line-oriented input, extract required data -- Examine the line and plan for whitespace, delimiters 6) Use methods to factor out common tasks Copyright 2013 by John Wiley & Sons. All rights reserved. Page 69 Summary: Input/Output q Use the Scanner class for reading text files. q When writing text files, use the PrintWriter class and the print/println/printf methods. q Close all files when you are done processing them. q Programs that start from the command line receive command line arguments in the main method. Copyright 2013 by John Wiley & Sons. All rights reserved. Page 70

Summary: Processing Text Files q The next method reads a string that is delimited by white space. q The Character class has methods for classifying characters. q The nextline method reads an entire line. q If a string contains the digits of a number, you use the Integer.parseInt or Double.parseDouble method to obtain the number value. q Programs that start from the command line receive the command line arguments in the main method. Copyright 2013 by John Wiley & Sons. All rights reserved. Page 71