TCSS 305 Stepp - PowerPoint PPT Presentation

1 / 49
About This Presentation
Title:

TCSS 305 Stepp

Description:

... user has typed input and pressed Enter, then it returns the ... hard drive. Creating a File object does not actually create that file on your hard drive. ... – PowerPoint PPT presentation

Number of Views:86
Avg rating:3.0/5.0
Slides: 50
Provided by: marty7
Category:

less

Transcript and Presenter's Notes

Title: TCSS 305 Stepp


1
TCSS 305 (Stepp)
  • Unit 0
  • File I/O, Arrays

2
Interactive Programs and File I/O with Scanner
and PrintStream
3
Interactive programs
  • We have written several programs that print
    output to the console.
  • It is also possible to read text input from the
    console.
  • The user running the program types the input into
    the console.
  • We can capture the input and use it as data in
    our program.
  • A program that processes input from the user is
    called an interactive program.
  • Interactive programs can be challenging
  • Computers and users think in very different ways.
  • Users tend to misbehave!

4
Input and System.in
  • We have now seen code that communicates with
    objects.
  • Example objects DrawingPanel, Graphics, Color
  • When we print text output to the console, we
    communicate with an object named System.out .
  • We call the println (or print) method of the
    System.out object to print a message to the
    console.
  • The object that holds the user's console input is
    named System.in . But it is not easy to use...

5
Scanner
  • Since System.in is not easy to use by itself, we
    will use a second object of a type named Scanner
    to help.
  • Once we construct the Scanner object, we can ask
    it to read various kinds of input from the
    console.
  • Constructing a Scanner object to read console
    input
  • Scanner ltnamegt new Scanner(System.in)
  • Example
  • Scanner console new Scanner(System.in)

6
Scanner as data source
  • Think of a Scanner like a faucet or showerhead
    that can be attached to a source of 'water'
    (data). In our case, the source of that data is
    System.in .
  • Like a faucet must be connected to a water
    source,the Scanner must be connected to a data
    sourceby writing (System.in) when constructing
    it.
  • The Scanner requires a file named Scanner.java
    that must be saved into the same folder as your
    program.
  • Scanner.java is available on the course web page.

7
Scanner methods
  • Methods of Scanner that we will use in this
    chapter
  • Each of these methods causes your program to
    pause until the user has typed input and pressed
    Enter, then it returns the typed value to your
    program.
  • (You may wish to review return values from last
    chapter.)

8
Example Scanner usage
  • public class ReadSomeInput
  • public static void main(String args)
  • System.out.print("How old are you? ")
  • int age
  • Scanner console new Scanner(System.in)
  • age console.nextInt()
  • System.out.println("Wow, you're " age)
  • System.out.println("That's quite old!")
  • Output (user input underlined)
  • How old are you? 14
  • Wow, you're 14
  • That's quite old!

9
Scanning tokens
  • token A unit of user input. Tokens are
    separated by whitespace (spaces, tabs, new
    lines).
  • Example If the user types the following
  • 23 3.14 John Smith "Hello world"
  • 45.2 19
  • The tokens in the input are the following, and
    can be interpreted as the given types
  • Token Type(s)
  • 1. 23 int, double, String
  • 2. 3.14 double, String
  • 3. John String
  • 4. Smith String
  • 5. "Hello String
  • 6. world" String
  • 7. 45.2 double, String
  • 8. 19 int, double, String

10
Consuming input
  • When the Scanner's methods are called, the
    Scanner reads and returns the next input value to
    our program.
  • If the type of the token isn't compatible with
    the type we requested, the program crashes.
  • Imagine the Scanner as having an invisible cursor
    that moves through all the user input.
  • As the scanner reads each input value, it
    advances forward through the user input until it
    has passed the given token.
  • This is called consuming the input token.
  • Key code consumed unconsumed last
    token
  • double pi console.nextDouble() //
    3.14
  • 23\t3.14 John Smith\t"Hello world"\n\t\t45.2 19

11
Consume input example
  • Example If the following input from the user has
    been typed,
  • 23 3.14 John Smith "Hello world"
  • 45.2 19
  • The Scanner views it as a linear stream of data,
    like the following
  • 23\t3.14 John Smith\t"Hello world"\n\t\t45.2
    19\n
  • The Scanner positions its 'cursor' at the start
    of the user input
  • 23\t3.14 John Smith\t"Hello world"\n\t\t45.2
    19\n
  • As we call the various next methods on the
    Scanner, the scanner moves forward
  • int x console.nextInt()
    // 23
  • 23\t3.14 John Smith\t"Hello world"\n\t\t45.2
    19\n
  • double pi console.nextDouble()
    // 3.14
  • 23\t3.14 John Smith\t"Hello world"\n\t\t45.2
    19\n
  • String word console.next()
    // "John"

12
Line-based input
  • The Scanner's nextLine method consumes and
    returns an entire line of input as a String.
  • The Scanner moves its cursor from its current
    position until it sees a \n new line character,
    and returns all text that was found.
  • The new line character is consumed but not
    returned.
  • Example
  • 23 3.14 John Smith "Hello world"
  • 45.2 19
  • String line1 console.nextLine()
  • 23\t3.14 John Smith\t"Hello world"\n\t\t45.2
    19\n
  • String line2 console.nextLine()
  • 23\t3.14 John Smith\t"Hello world"\n\t\t45.2
    19\n


13
Mixing line-based with tokens
  • It is not generally recommended to use nextLine
    in combination with the other next__ methods,
    because confusing results occur.
  • 23 3.14Joe "Hello world" 45.2 19
  • int n console.nextInt()
    // 2323\t3.14\nJoe\t"Hello world"\n\t\t45.2
    19\n
  • double x console.nextDouble()
    // 3.1423\t3.14\nJoe\t"Hello world"\n\t\t45.2
    19\n
  • // User intends to grab the John Smith "Hello
    world" line// but instead receives an empty
    line!String line console.nextLine()
    // ""23\t3.14\nJoe\t"Hello
    world"\n\t\t45.2 19\n
  • // Calling nextLine again will get the line we
    wanted.String line2 console.nextLine() //
    "Joe\t\"Hello world\""23\t3.14\nJoe\t"Hello
    world"\n\t\t45.2 19\n

14
Line-and-token example
  • Here's another example of the confusing behavior
  • Scanner console new Scanner(System.in)
  • System.out.print("Enter your age ")
  • int age console.nextInt()
  • System.out.print("Now enter your name ")
  • String name console.nextLine()
  • System.out.println(name " is " age " years
    old.")
  • Log of execution (user input underlined)
  • Enter your age 12
  • Now enter your name Marty Stepp
  • is 12 years old.
  • Why?
  • User's overall input 12\nMarty Stepp
  • After nextInt() 12\nMarty Stepp
  • After nextLine() 12\nMarty Stepp

15
File objects
  • Java's File class represents files on the
    user'shard drive.
  • Creating a File object does not actually create
    that file on your hard drive.
  • When we want to read data out of a file, we
    create a File object representing that file and
    open it with a Scanner.
  • Creating a Scanner for a File, general syntax
  • Scanner ltnamegt new Scanner(new File("ltfile
    namegt"))
  • Example
  • Scanner input new Scanner(new
    File("numbers.txt"))
  • The File class is in Java's java.io package, so
    we must write this at the top of our program
  • import java.io.

16
Exceptions, throwing
  • exception A Java object that represents a
    program error.
  • checked exception An error that Java forces us
    to handle in our program. Otherwise the program
    will not compile.
  • Java forces us to specify what our program
    should do to handle potential failures when
    opening a file.
  • throws clause Keywords that can be added to the
    header of our methods to explain to Java that we
    plan NOT to handle file input failures. (We'll
    just let the program crash in such a case.)
  • Throws clause, general syntax
  • public static lttypegt ltnamegt(ltparamsgt) throws
    lttypegt
  • Example
  • public static void main(String args)
  • throws
    FileNotFoundException

17
Sample file input program
  • import java.io.
  • // Displays each number in the given file,
  • // and displays their sum at the end.
  • public class Echo2
  • public static void main(String args)
  • throws
    FileNotFoundException
  • Scanner input new Scanner(new
    File("numbers.dat"))
  • double sum 0.0
  • for (int i 1 i lt 5 i)
  • double next input.nextDouble()
  • System.out.println("number " i "
    " next)
  • sum next
  • System.out.println("Sum " sum)
  • Input File numbers.dat Output
  • 308.2 14.9 7.4 number 1 308.2

18
Testing before reading
  • The Scanner has useful methods for testing to see
    what the next input token will be
  • You can call these methods as a condition of an
    if statement or loop.

19
Example test before read
  • import java.io.
  • // Displays each number in the given file,
  • // and displays their sum at the end.
  • public class Echo3
  • public static void main(String args)
  • throws
    FileNotFoundException
  • Scanner input new Scanner(new
    File("numbers.dat"))
  • double sum 0.0
  • while (input.hasNextDouble())
  • double next input.nextDouble()
  • System.out.println("number " i "
    " next)
  • sum next
  • System.out.println("Sum " sum)
  • Input File numbers.dat Output
  • 308.2 14.9 7.4 number 1 308.2

20
Files and input cursor
  • Recall that a Scanner views all input as a stream
    of characters, which it processes with its input
    cursor
  • 308.2 14.9 7.4\n2.8\n\n\n3.9 4.7 -15.4\n2.8\n
  • Each call to next, nextInt, nextDouble advances
    the cursor to the end of the current token
    (whitespace-separated)
  • input.nextDouble()
  • 308.2 14.9 7.4\n2.8\n\n\n3.9 4.7 -15.4\n2.8\n
  • input.nextDouble()
  • 308.2 14.9 7.4\n2.8\n\n\n3.9 4.7 -15.4\n2.8\n

21
File names
  • Relative path "readme.txt" or "input/readme.txt"
  • Absolute path "C\\Documents\\smith\\hw6\\input\\
    readme.txt"
  • In TextPad editor (and most editors), when you
    construct a File object with just a file name,
    Java assumes you mean a file in the current
    directory.
  • Scanner input new Scanner(new
    File("readme.txt"))
  • If our program is in the folder C\Documents and
    Settings\johnson\hw6, that is where Java will
    look for readme.txt.
  • In DrJava, when you construct a File object with
    just a relative path, Java assumes you mean a
    file in the directory where DrJava is installed
    on your hard drive.
  • DrJava does not find your file unless you put the
    input file in the same folder as the DrJava
    program (on Mac, usually /Applications), or
    specify its absolute path. Argh!

22
Line-by-line processing
  • Scanners have a method named nextLine that
    returns text from the input cursor's current
    position forward to the nearest \n new line
    character.
  • You can use nextLine to break up a file's
    contents into each line and examine the lines
    individually.
  • Reading a file line-by-line, general syntax
  • Scanner input new Scanner(new File("ltfile
    namegt"))
  • while (input.hasNextLine())
  • String line input.nextLine()
  • ltprocess this line...gt

23
Processing one line
  • Often the contents of each line are themselves
    complex, so we want to tokenize each individual
    line using its own Scanner.
  • Example file contents
  • Susan 12.5 8.1 7.6 3.2
  • Brad 4.0 11.6 6.5 2.7 12
  • Jennifer 8.0 8.0 8.0 8.0 7.5
  • A Scanner can be constructed to tokenize a
    particular String, such as one line of an input
    file.
  • Scanner ltnamegt new Scanner(ltStringgt)
  • Processing complex input, general syntax
  • Scanner input new Scanner(new File("ltfile
    namegt"))
  • while (input.hasNextLine())
  • String line input.nextLine()
  • Scanner lineScan new Scanner(line)
  • ltprocess this line...gt

24
Line-based input, cont'd.
  • Often we have to write programs that scan through
    a file, finding the appropriate piece of data,
    and process only that piece
  • Enter a name Brad
  • Brad worked 36.8 hours (7.36 hours/day)
  • Often we have files with a particular token of
    importance on each line, followed by more data
  • hours.txt
  • Susan 12.5 8.1 7.6 3.2
  • Brad 4.0 11.6 6.5 2.7 12
  • Jennifer 8.0 8.0 8.0 8.0 7.5

25
Searching a file for a line
  • Recall reading a file line-by-line, general
    syntax
  • Scanner input new Scanner(new File("ltfile
    namegt"))
  • while (input.hasNextLine())
  • String line input.nextLine()
  • Scanner lineScan new Scanner(line)
  • ltprocess this line...gt
  • For this program
  • Scanner input new Scanner(new
    File("hours.txt"))
  • while (input.hasNextLine())
  • String line input.nextLine()
  • Scanner lineScan new Scanner(line)
  • String name lineScan.next()
  • ... if this is the name we want, add up their
    hours

26
Prompting for a file name
  • Instead of writing the file's name into the
    program as a String, we can ask the user to tell
    us the file name to use.
  • Here is one case where we may wish to use
    nextLine on a console Scanner, because a file
    name might have spaces in it.
  • Scanner console new Scanner(System.in)
  • System.out.print("Type a file name to use ")
  • String filename console.nextLine()
  • // open the file
  • Scanner input new Scanner(new File(filename))

27
File not found
  • What if the user types a file name that does not
    exist?
  • We can use the exists() method of the File object
    to make sure that file exists and can be read.
  • Scanner console new Scanner(System.in)
  • System.out.print("Type a file name to use ")
  • String filename console.nextLine()
  • File file new File(filename)
  • while (!file.exists())
  • System.out.println("File not found!")
  • System.out.print("Type a file name to use
    ")
  • String filename console.nextLine()
  • file new File(filename)
  • Scanner input new Scanner(file)
  • Output
  • Type a file name to use hourz.text
  • File not found!
  • Type a file name to use h0urz.txt

28
Complex multi-line records
  • Sometimes the data in the file consists of
    'records', each of which is a group of
    information that may occupy multiple lines
  • grades.dat
  • Erica Kane
  • 3 2.8 4 3.9 3 3.1
  • Greenlee Smythe
  • 3 3.9 3 4.0 4 3.9
  • Ryan Laveree
  • 2 4.0 3 3.6 4 3.8 1 2.8
  • Adam Chandler
  • 3 3.0 4 2.9 3 3.2 2 2.5
  • Adam Chandler, Jr
  • 4 1.5 5 1.9
  • How can we process one or all of these records?

29
Output to files
  • Java has an object named PrintStream (in the
    java.io package) that allows you to print output
    into a destination, which can be a file.
  • System.out is also a PrintStream, so any methods
    you have used on System.out (such as print,
    println) will work on every PrintStream.
  • Printing into an output file, general syntax
  • PrintStream ltnamegt new PrintStream(
  • new FileOutputStream("ltfile namegt"))
  • ...
  • Example
  • PrintStream output new PrintStream(
  • new FileOutputStream("output.txt"))
  • output.println("Hello, file!")

30
Arrays
31
Too many values...
  • How would we implement a program such as this?
  • How many numbers 5
  • Number 1 2
  • Number 2 7
  • Number 3 17
  • Number 4 -1
  • Number 5 64
  • Here are the numbers you typed
  • Number 1 2
  • Number 2 7
  • Number 3 17
  • Number 4 -1
  • Number 5 64
  • We don't know how many int variables we should
    declare in advance... it could be very many!

32
Arrays
  • array A single variable that can store many
    values of the same type.
  • element One value in an array.
  • index A 0-based integer, which is used to access
    an element from an array.
  • We usually draw arrays as horizontal grids.
  • An array of integers

33
Array declaration
  • Declaring/initializing an array, general syntax
  • lttypegt ltnamegt new lttypegt ltlengthgt
  • The length of the array is specified between
    brackets.
  • Example
  • int numbers new int10
  • Example
  • double grades new double6

34
Accessing array elements
  • Assigning a value to an array element, general
    syntax
  • ltarray namegt ltindexgt ltvaluegt
  • Example
  • numbers0 27
  • numbers3 -1
  • When arrays are initially constructed, every
    element has a 0-equivalent value.
  • int 0
  • double 0.0
  • boolean false
  • char '\0' (the "null character")
  • String or other object null (null means "no
    object")

35
Arrays and for loops
  • Arrays are very commonly used with for loops that
    pass over each element and process it in some
    way
  • Example (print each element of an array)
  • for (int i 0 i lt 10 i)
  • System.out.print(numbersi " ")
  • Output
  • 27 0 0 -1 0 0 0 0 0 0
  • Example (store squared numbers in an array)
  • for (int i 0 i lt 10 i)
  • numbersi i i

36
The .length field
  • An array has a field named .length that returns
    its total number of elements.
  • This is preferred to be used instead of
    hard-coding the array's length as a literal
    value. (Why?)
  • Example
  • for (int i 0 i lt numbers.length i)
  • System.out.print(numbersi " ")
  • Output
  • 0 1 4 9 16 25 36 49 64 81

37
Array initialization shortcut
  • Quick array initialization, general syntax
  • lttypegt ltnamegt ltvaluegt, ltvaluegt, ...,
    ltvaluegt
  • Example
  • int numbers 12, 49, -2, 26, 5, 17, -6, 84,
    72, 3
  • This syntax is useful when you know in advance
    what the array's elements will be.

38
Array practice problem
  • What are the contents of the array a after the
    following code?
  • int a 2, 5, 1, 6, 14, 7, 9
  • for (int i 1 i lt a.length i)
  • ai ai - 1

39
Limitations of arrays
  • An array cannot be directly printed by println
  • Example
  • int numbers new int10
  • System.out.println(numbers)
  • Output
  • I_at_1cb52ae
  • Arrays cannot be compared correctly with or
    equals
  • Example
  • int numbers1 new int10
  • int numbers2 new int10
  • System.out.println(numbers1 numbers2)
  • Output
  • false

40
More array limitations
  • An array's size cannot be modified after it is
    created.
  • The .length field is read-only you cannot change
    it.
  • Example
  • int numbers new int10
  • numbers.length 20 // does not compile!
  • You can instead create a new larger array and
    copy the elements over into it.
  • It is illegal to access an array element with an
    index that is less than 0 or greater than its
    .length - 1.
  • If you do so, your program will crash with an
    exception.
  • Example
  • int numbers new int10
  • System.out.println(numbers10) // kaboom!

41
Why are arrays useful?
  • We can use arrays to store a large amount of data
    without declaring many variables.
  • Example Read in a file of 1000 numbers, then
    print out the numbers in reverse order.
  • Arrays can help us to group related data into
    elements.
  • Example For a given school exam, open a file
    full of exam scores and count up how many
    students got each score from 0 through 100.
  • Arrays let us hold on to data and access it in
    random order.
  • Example Read a file full of babies' names, store
    each name's data as an element in a large array,
    and then examine it later to find names that the
    user types.

42
Arrays as parameters
  • An array can be passed as a parameter to a
    method.
  • Example
  • int iq new int3
  • iq0 126
  • iq1 167
  • iq2 95
  • int max getMaxValue(iq)
  • System.out.println("Max " max)
  • ...
  • public static int getMaxValue(int array)
  • int max array0
  • for (int i 1 i lt array.length i)
  • if (arrayi gt max)
  • max arrayi
  • return max

43
Arrays as parameters, contd.
  • When an array is passed as a parameter, it is
    passed as a reference (similar to objects).
  • If the method modifies elements of its array
    parameter, the changes will also be seen in the
    original array.
  • Example
  • int iq new int3
  • iq0 126
  • iq1 167
  • iq2 95
  • destroy(iq)
  • System.out.println(array0 " " array1)
  • ...
  • public static void destroy(int array)
  • for (int i 0 i lt array.length i)
  • arrayi 0 // ha ha!
  • Output
  • 0 0

44
Array practice problems
  • Write a method named print that accepts an array
    of integers as its parameter and prints the
    elements of the array in the following format
  • 7, -2, 46, 3, 55
  • Write a method named equal that accepts 2 arrays
    of integers as its parameters and returns whether
    those two arrays contain exactly the same
    elements in the same order.

45
String methods with arrays
  • These String methods return arrays
  • String s "long book"

46
Arrays of objects
  • Recall when you construct an array of primitive
    values like ints, the elements' values are all
    initialized to 0.
  • What is the equivalent of 0 for objects?
  • When you construct an array of objects (such as
    Strings), each element initially stores a special
    reference value called null.
  • null means 'no object'
  • Your program will crash if you try to call
    methods on a null reference.
  • String words new String5

47
The dreaded 'null pointer'
  • Null array elements often lead to program
    crashes
  • String words new String5
  • System.out.println(words0)
  • words0 words0.toUpperCase() // kaboom!
  • Output
  • null
  • Exception in thread "main" java.lang.NullPointerE
    xception
  • at ExampleProgram.main(DrawPolyline.java
    8)
  • The array elements should be initialized somehow
  • for (int i 0 i lt words.length i)
  • wordsi "this is string " (i 1)
  • words0 words0.toUpperCase() // okay now

48
Java's Arrays class
  • The Arrays class in package java.util has several
    useful static methods for manipulating arrays

49
Arrays class example
  • Searching and sorting numbers in an array
  • int numbers 23, 13, 480, -18, 75
  • int index Arrays.binarySearch(numbers, -18)
  • System.out.println("index " index)
  • Output
  • index 3
  • Arrays.sort(numbers)
  • index Arrays.binarySearch(numbers, -18)
  • System.out.println("index " 0)
  • for (int i 0 i lt numbers.length i)
  • System.out.print(numbersi " ")
  • Output
  • -18 13 23 75 480
Write a Comment
User Comments (0)
About PowerShow.com