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

Size: px
Start display at page:

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

Transcription

1 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

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:// 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!, , 3.8x104, or 5.2e6? In our world strings delineated by quota3ons: University of S3rling 4

3 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

4 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

5 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

6 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

7 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: 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); H a r r y Copyright 2013 by John Wiley & Sons. Page 14

8 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 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); // Get the names of the couple 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(); // Compute and display the inscription 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.

9 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 " and the delimiter '/', the individual tokens in that string would be " " "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

10 StringTokenizer Example 2 String input=" 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: 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

11 Example: String.split String input=" 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 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(); // 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

12 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: 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: spaces 2 spaces The %10.2f is called a format specifier Page 24

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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 India United States nextline() reads one line and consumes the ending \n Copyright 2013 by John Wiley & Sons. All rights reserved. Page 50

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

27 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 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 String pop = ; int populationvalue = Integer.parseInt(pop); String pricestring = 3.95 ; int price = Double.parseInt(priceString); Copyright 2013 by John Wiley & Sons. All rights reserved. Page 54

28 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

29 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 India There is a newline at the end of each line After reading 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

30 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

31 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

32 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

33 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

34 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

35 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

36 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

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

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I

More information

JAVA.UTIL.SCANNER CLASS

JAVA.UTIL.SCANNER CLASS JAVA.UTIL.SCANNER CLASS http://www.tutorialspoint.com/java/util/java_util_scanner.htm Copyright tutorialspoint.com Introduction The java.util.scanner class is a simple text scanner which can parse primitive

More information

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

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources

More information

Object-Oriented Programming in Java

Object-Oriented Programming in Java CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio

More information

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch16 Files and Streams PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for

More information

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

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input

More information

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

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output Chapter 2 Console Input and Output System.out.println for console output System.out is an object that is part of the Java language println is a method invoked dby the System.out object that can be used

More information

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

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems sjmaybank@dcs.bbk.ac.uk Spring 2015 Week 2b: Review of Week 1, Variables 16 January 2015 Birkbeck

More information

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

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab. Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command

More information

Using Files as Input/Output in Java 5.0 Applications

Using Files as Input/Output in Java 5.0 Applications Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead

More information

13 File Output and Input

13 File Output and Input SCIENTIFIC PROGRAMMING -1 13 File Output and Input 13.1 Introduction To make programs really useful we have to be able to input and output data in large machinereadable amounts, in particular we have to

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install

More information

Chapter 3. Input and output. 3.1 The System class

Chapter 3. Input and output. 3.1 The System class Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use

More information

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

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

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

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10) File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The

More information

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

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

AP Computer Science Static Methods, Strings, User Input

AP Computer Science Static Methods, Strings, User Input AP Computer Science Static Methods, Strings, User Input Static Methods The Math class contains a special type of methods, called static methods. A static method DOES NOT operate on an object. This is because

More information

6.1. Example: A Tip Calculator 6-1

6.1. Example: A Tip Calculator 6-1 Chapter 6. Transition to Java Not all programming languages are created equal. Each is designed by its creator to achieve a particular purpose, which can range from highly focused languages designed for

More information

Comp 248 Introduction to Programming

Comp 248 Introduction to Programming Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

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

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane. Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6 Handout 3 Strings and String Class. Input/Output with JOptionPane. Strings In Java strings are represented with a class type String. Examples:

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print

More information

Introduction to Java. CS 3: Computer Programming in Java

Introduction to Java. CS 3: Computer Programming in Java Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods

More information

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

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

Lecture 5: Java Fundamentals III

Lecture 5: Java Fundamentals III Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper

More information

Week 1: Review of Java Programming Basics

Week 1: Review of Java Programming Basics Week 1: Review of Java Programming Basics Sources: Chapter 2 in Supplementary Book (Murach s Java Programming) Appendix A in Textbook (Carrano) Slide 1 Outline Objectives A simple Java Program Data-types

More information

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input

More information

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

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand: Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

More information

Some Scanner Class Methods

Some Scanner Class Methods Keyboard Input Scanner, Documentation, Style Java 5.0 has reasonable facilities for handling keyboard input. These facilities are provided by the Scanner class in the java.util package. A package is a

More information

CS106A, Stanford Handout #38. Strings and Chars

CS106A, Stanford Handout #38. Strings and Chars CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print

More information

AP Computer Science File Input with Scanner

AP Computer Science File Input with Scanner AP Computer Science File Input with Scanner Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 6 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ ) Input/output

More information

java Features Version April 19, 2013 by Thorsten Kracht

java Features Version April 19, 2013 by Thorsten Kracht java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................

More information

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

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

More information

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

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight

More information

Visit us at www.apluscompsci.com

Visit us at www.apluscompsci.com Visit us at www.apluscompsci.com Full Curriculum Solutions M/C Review Question Banks Live Programming Problems Tons of great content! www.facebook.com/apluscomputerscience Scanner kb = new Scanner(System.in);

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 29 / 2014 Instructor: Michael Eckmann Today s Topics Comments and/or Questions? import user input using JOptionPane user input using Scanner psuedocode import

More information

Event-Driven Programming

Event-Driven Programming Event-Driven Programming Lecture 4 Jenny Walter Fall 2008 Simple Graphics Program import acm.graphics.*; import java.awt.*; import acm.program.*; public class Circle extends GraphicsProgram { public void

More information

Unit 6. Loop statements

Unit 6. Loop statements Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now

More information

Programming Languages CIS 443

Programming Languages CIS 443 Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception

More information

Quick Introduction to Java

Quick Introduction to Java Quick Introduction to Java Dr. Chris Bourke Department of Computer Science & Engineering University of Nebraska Lincoln Lincoln, NE 68588, USA Email: cbourke@cse.unl.edu 2015/10/30 20:02:28 Abstract These

More information

Building a Multi-Threaded Web Server

Building a Multi-Threaded Web Server Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

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

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash IMDB Data Set Topics: Parsing Input using Scanner class Atul Prakash IMDB Data Set Consists of several files: movies.list: contains actors.list: contains aka-titles.list:

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Sample CSE8A midterm Multiple Choice (circle one)

Sample CSE8A midterm Multiple Choice (circle one) Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names

More information

Basics of Java Programming Input and the Scanner class

Basics of Java Programming Input and the Scanner class Basics of Java Programming Input and the Scanner class CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Course Intro Instructor Intro Java Intro, Continued

Course Intro Instructor Intro Java Intro, Continued Course Intro Instructor Intro Java Intro, Continued The syllabus Java etc. To submit your homework, do Team > Share Your repository name is csse220-200830-username Use your old SVN password. Note to assistants:

More information

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

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 21 10/16/2012 09:29 AM Java - A First Glance 2 of 21 10/16/2012 09:29 AM programming languages

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright

More information

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

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc. WA2099 Introduction to Java using RAD 8.0 Student Labs Web Age Solutions Inc. 1 Table of Contents Lab 1 - The HelloWorld Class...3 Lab 2 - Refining The HelloWorld Class...20 Lab 3 - The Arithmetic Class...25

More information

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

Basic Programming and PC Skills: Basic Programming and PC Skills: Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of

More information

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

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in

More information

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui

More information

Simple Java I/O. Streams

Simple Java I/O. Streams Simple Java I/O Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for data (sometimes both) An input stream may be associated with the keyboard An

More information

Reading Input From A File

Reading Input From A File Reading Input From A File In addition to reading in values from the keyboard, the Scanner class also allows us to read in numeric values from a file. 1. Create and save a text file (.txt or.dat extension)

More information

Programming and Data Structures with Java and JUnit. Rick Mercer

Programming and Data Structures with Java and JUnit. Rick Mercer Programming and Data Structures with Java and JUnit Rick Mercer ii Chapter Title 1 Program Development 2 Java Fundamentals 3 Objects and JUnit 4 Methods 5 Selection (if- else) 6 Repetition (while and for

More information

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

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 Chapter 10 File I/O Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream is called an input stream

More information

Introduction to Java Lecture Notes. Ryan Dougherty redoughe@asu.edu

Introduction to Java Lecture Notes. Ryan Dougherty redoughe@asu.edu 1 Introduction to Java Lecture Notes Ryan Dougherty redoughe@asu.edu Table of Contents 1 Versions....................................................................... 2 2 Introduction...................................................................

More information

Chapter 2 Basics of Scanning and Conventional Programming in Java

Chapter 2 Basics of Scanning and Conventional Programming in Java Chapter 2 Basics of Scanning and Conventional Programming in Java In this chapter, we will introduce you to an initial set of Java features, the equivalent of which you should have seen in your CS-1 class;

More information

CS 121 Intro to Programming:Java - Lecture 11 Announcements

CS 121 Intro to Programming:Java - Lecture 11 Announcements CS 121 Intro to Programming:Java - Lecture 11 Announcements Next Owl assignment up, due Friday (it s short!) Programming assignment due next Monday morning Preregistration advice: More computing? Take

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

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

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

More information

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

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

More information

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

JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved. 1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,

More information

LOOPS CHAPTER CHAPTER GOALS

LOOPS CHAPTER CHAPTER GOALS jfe_ch04_7.fm Page 139 Friday, May 8, 2009 2:45 PM LOOPS CHAPTER 4 CHAPTER GOALS To learn about while, for, and do loops To become familiar with common loop algorithms To understand nested loops To implement

More information

10 Java API, Exceptions, and Collections

10 Java API, Exceptions, and Collections 10 Java API, Exceptions, and Collections Activities 1. Familiarize yourself with the Java Application Programmers Interface (API) documentation. 2. Learn the basics of writing comments in Javadoc style.

More information

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

Programming in Java. What is in This Chapter? Chapter 1 Chapter 1 Programming in Java What is in This Chapter? This first chapter introduces you to programming JAVA applications. It assumes that you are already familiar with programming and that you have taken

More information

Crash Course in Java

Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is

More information

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

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime? CSCI 312 - DATA COMMUNICATIONS AND NETWORKS FALL, 2014 Assignment 4 Working as a group. Working in small gruops of 2-4 students. When you work as a group, you have to return only one home assignment per

More information

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

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java CS1020 Data Structures and Algorithms I Lecture Note #1 Introduction to Java Objectives Java Basic Java features C Java Translate C programs in CS1010 into Java programs 2 References Chapter 1 Section

More information

Files and input/output streams

Files and input/output streams Unit 9 Files and input/output streams Summary The concept of file Writing and reading text files Operations on files Input streams: keyboard, file, internet Output streams: file, video Generalized writing

More information

Java Programming Fundamentals

Java Programming Fundamentals Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few

More information

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

COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005. Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 Term Test #2 COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005 Family Name: Given Name(s): Student Number: Question Out of Mark A Total 16 B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 C-1 4

More information

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

AP Computer Science Java Mr. Clausen Program 9A, 9B AP Computer Science Java Mr. Clausen Program 9A, 9B PROGRAM 9A I m_sort_of_searching (20 points now, 60 points when all parts are finished) The purpose of this project is to set up a program that will

More information

Using Two-Dimensional Arrays

Using Two-Dimensional Arrays Using Two-Dimensional Arrays Great news! What used to be the old one-floor Java Motel has just been renovated! The new, five-floor Java Hotel features a free continental breakfast and, at absolutely no

More information

Java Basics: Data Types, Variables, and Loops

Java Basics: Data Types, Variables, and Loops Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

More information

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

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1 Interactive Programs with Scanner reading: 3.3-3.4 1 Interactive programs We have written programs that print console

More information

Arrays. Introduction. Chapter 7

Arrays. Introduction. Chapter 7 CH07 p375-436 1/30/07 1:02 PM Page 375 Chapter 7 Arrays Introduction The sequential nature of files severely limits the number of interesting things you can easily do with them.the algorithms we have examined

More information

Chapter 8. Living with Java. 8.1 Standard Output

Chapter 8. Living with Java. 8.1 Standard Output 82 Chapter 8 Living with Java This chapter deals with some miscellaneous issues: program output, formatting, errors, constants, and encapsulation. 8.1 Standard Output The Java runtime environment (JRE)

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch15 Exception Handling PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for

More information

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

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

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

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER Reading text data from keyboard using DataInputStream As we have seen in introduction to streams, DataInputStream is a FilterInputStream

More information

Hypercosm. Studio. www.hypercosm.com

Hypercosm. Studio. www.hypercosm.com Hypercosm Studio www.hypercosm.com Hypercosm Studio Guide 3 Revision: November 2005 Copyright 2005 Hypercosm LLC All rights reserved. Hypercosm, OMAR, Hypercosm 3D Player, and Hypercosm Studio are trademarks

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, 4.3-4.4 self-check: Ch. 4 #12, 15 exercises: Ch. 4 #15, 16 videos: Ch. 3 #3 1 Objects and classes object: An entity that contains: data

More information

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

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved. Chapter 20 Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved. 20.1 Readers, Writers, and Streams Two ways to store data: Text

More information

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.

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. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Introduction to Python

Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

More information

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

Explain the relationship between a class and an object. Which is general and which is specific? A.1.1 What is the Java Virtual Machine? Is it hardware or software? How does its role differ from that of the Java compiler? The Java Virtual Machine (JVM) is software that simulates the execution of a

More information

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

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius Programming Concepts Practice Test 1 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius 2) Consider the following statement: System.out.println("1

More information