Input and Output and Arrays Robots Learning to Program with Java - - PowerPoint PPT Presentation

input and output and arrays
SMART_READER_LITE
LIVE PREVIEW

Input and Output and Arrays Robots Learning to Program with Java - - PowerPoint PPT Presentation

Input and Output and Arrays Robots Learning to Program with Java Byron Weber Becker chapter 9 and 10 Announcements (Nov 7 th ) Reading for next Monday Ch 10 ( not covering 10.1.8, 10.7) Program#7 Clarification Driver


slide-1
SLIDE 1

Input and Output and Arrays

Robots Learning to Program with Java Byron Weber Becker

chapter 9 and 10

slide-2
SLIDE 2

Announcements (Nov 7th )

 Reading for next Monday

 Ch 10 (not covering 10.1.8, 10.7)

 Program#7

 Clarification  Driver

 Exam#2 scheduled for Nov 9th (Wed 8PM)

 Sign-up for make-up exam (talk to the instructor by

Monday)

slide-3
SLIDE 3

Exam#2

 Change of room

 The 168 exam 2 next week will be in CVA (Center for the

Visual Arts) 149 instead of STV 101.

 http://maps.illinoisstate.edu/locations/center_for_the_vis

ual_arts_cva.shtml

 Coverage (practically comprehensive)

 ~ program6, ~ Ch7 (including console I/O using Scanner,

Sytem.in, and System.out.print*), ~ Lab10

 few questions (one or two) related to Robot class  Main focus: control structure, write your own classes

, inheritance

slide-4
SLIDE 4

Facebook using Java?

 Let’s start with “Person” class

 “String” name  Four “Person” objects to represent four friends  Implement toString()

slide-5
SLIDE 5

Lab example

 Person class

slide-6
SLIDE 6

Review: Some Scanner Methods

 String next()

Finds and returns the next complete token from this scanner.

 double nextDouble()

Scans the next token of the input as a double – will produce an error if the token is not numeric.

 int nextInt()

Scans the next token of the input as an int – will produce an error if the token is not numeric.

 String nextLine()

Advances this scanner past the next line return and returns the data that was skipped.

slide-7
SLIDE 7

Review: Some Scanner Predicates

 boolean hasNext()

Returns true if this scanner has another token in its input stream.

 boolean hasNextDouble()

Returns true if the next token in this scanner's input stream can be interpreted as a double value using nextDouble()

 boolean hasNextInt()

Returns true if the next token in the input stream can be interpreted as an integer value using nextInt()

 boolean hasNextLine()

Returns true if there is another line return in the input stream of this scanner.

slide-8
SLIDE 8

Dumping the Input Buffer

 When you combine the use of nextLine() and any of the

  • ther 3 next methods you must take care with new line

characters.

 Sometimes you need to dump the input buffer.  This can be done using

scan.nextLine();

slide-9
SLIDE 9

The Input Buffer

 The input buffer holds the characters that are being read –

whether from the keyboard or from a file.

 In the Scanner class, next(), nextInt, and nextDouble read

up to or over any new line character (ignoring it).

 The nextLine() method reads through the next new line

character and stops at the front of the next line. The new line character is dropped, not returned.

slide-10
SLIDE 10

Practice**

 Write a main method that will allow the user to enter the

names (storing the full name) and ages of 5 students.

 Assume we have a Student class with a constructor that takes

a String and int: public Student(String name, int age)

 Collect and store the data in 5 Student variables.

slide-11
SLIDE 11

Review: File Reading

 The Scanner class can be used to read from a file (instead of

the keyboard) with a one small change.

 Instead of declaring our Scanner as

Scanner scan = new Scanner(System.in);

We will declare it with a file.

 First we create the File using

File file = new File(“input.txt”); Scanner fScan = new Scanner(file);

slide-12
SLIDE 12

Same Old Methods

 Whether reading from a file or from a keyboard, the Scanner

methods work the same.

 The biggest difference is that from a file you have no user

prompts…

slide-13
SLIDE 13

Practice

 Write a main method that will read the file below

(alternating lines are integer or text) and echo it to the screen

 Use nextLine to read the text lines and nextInt for lines

with numbers only

 File name is input.txt

1 this is a text line 2 this is another text line 3 this is the last text line

slide-14
SLIDE 14

Writing to a File

 There are a number of ways to write to a file  We will use a PrintWriter object  Once the file has been opened, the PrintWriter object works

just like using System.out

slide-15
SLIDE 15

Exception handeling

 The try-catch block

try {

// attempt to do something that might error out

} catch (ExeptionType excp) {

// print some error message for easy debugging

}

slide-16
SLIDE 16

Opening a File for Output

PrintWriter out = null; try {

  • ut = new PrintWriter(“fileName.txt");

System.out.println("file created and open"); } catch (FileNotFoundException excp) { System.out.println(" fileName.txt could not be opened for output"); excp.printStackTrace(); }

slide-17
SLIDE 17

Practice**

 File name is input.txt

1 this is a text line 2 this is another text line 3 this is the last text line

 File name is output.txt

this is a text line 1 this is another text line 2 this is the last text line 3

  • Change the last practice problem so it

first reads 2 lines from the input file, then switches their order to create an

  • utput file
slide-18
SLIDE 18

More Practice**

 Write a main method that requests data from the user and

writes it to a file – one data element per line.

 The data will be

 A person’s full name – which we will store in all uppercase

letters regardless of how it is entered

 A single word nickname  Their current age (as an integer)

slide-19
SLIDE 19

Constructor that takes a Scaner**

 When you are creating a class that will be read from a file it

is typical to create a constructor that accepts a Scanner and reads a single record from an opened file

 The constructor will NOT open or close the file – simply

read the next record

slide-20
SLIDE 20

Method that takes a Scanner

 Instead of using the constructor you can create a method for

reading a single record

 When using such a method you must take care not to create

aliases

slide-21
SLIDE 21

Writing a Record

 Regardless of which version of reading you use (in a

constructor or a method) you need to create a method for writing a single record to an open file

 This is basically the opposite of the reading method and

should create a record in the same format

 This method will not open or close the file

slide-22
SLIDE 22

Tracing Practice

Scanner infile = new Scanner(new File(“input.txt”)); int val1, val2; int curVal = infile.nextInt(); val1 = curVal; val2 = curVal; while (infile.hasNext()) { curVal = infile.nextInt(); if (val1 < curVal) { val1 = curVal; } else if (val2 > curVal) { val2 = curVal; } } System.out.println(“Val1: ” + val1 + “\nVal2: ” + val2);

slide-23
SLIDE 23

Pseudocode Practice

 Write pseudocode to read a file that contains course id, room

capacity, and current enrollment, in that order, on each line of the file.

 Read in each row from the file and display the data.  In addition, give the number of seats available and a message

stating whether or not the class is full.

 Process the entire file.  Example file:

Itk168 40 27 Itk261 25 25 Itk150 220 219

slide-24
SLIDE 24

Coding Practice

 Write code to read integers from the keyboard and count the

number of odd integers entered.

 Input should stop when the user enters -1.

 Do not count the -1 as one of the odd integers that you’re

counting.

 Prompt the user for input.  Be sure to declare all needed variables.

slide-25
SLIDE 25

Arrays

ITK 168 Spring 2011

Robots Learning to Program with Java Byron Weber Becker

chapter 10

slide-26
SLIDE 26

Chapter Objectives

 Store data in an array

 Primatives  Objects

 Access a single element  Process all elements  Search for a particular element  Insert element

slide-27
SLIDE 27

Containers

 There are a number of “containers” used in programming  An Array is one type of container

 Can contain primitive or objective data  Elements are stored consecutively and numbered – starting at

zero and counting to one less than the capacity

 Has a maximum capacity and current size

slide-28
SLIDE 28

Declaring and Filling Arrays

 Declaring an array with no initial elements

int[] integers = new int[5]; double[] prices = new double[10]; Person[] people = new Person[25];

 Filling an array at declaration

int[] numbers = {1, 2, 3, 4, 5};

slide-29
SLIDE 29

Walking Through an Array

 Suppose we have an array of up to 100 integers (of unknown

contents) originally declared as int[] scores = new int[100]; int numRecords = 0;

 Suppose we want to

 Print the contents  Average the contents  Print the largest and smallest value  Find the first location of a value

slide-30
SLIDE 30

For-each

 Typically used to walk through the entire array – assumes the

array has been filled completely

 Take care with arrays of objects!

for(Person person : addressBook) { System.out.println(person); }

slide-31
SLIDE 31

Practice

 Declare an array of integers to hold up to 100 scores  Code a loop to get scores from the user until they enter -99

to quit

 Be sure not to process -99

 Print the scores in 4 columns across the rows  Print the highest score, lowest score, and average

slide-32
SLIDE 32

More Practice

 Declare an array to hold up to 10 characters  Get the 10 characters from your user – requiring all 10 to be

entered

 Print the characters on one row in the order entered  Print the characters on one row in the opposite order

entered

 Look for the letter ‘s’ – if entered, return the first index

location, if not return -1