1 of 27

Lecture 7 - CS159 –Arrays+Scanner

Due this week:

Review your Exam 1 grade�Fri 11pm Lab6�Sun HW 3

Tue Reading Week 6

Fri Quiz 6 / Lab 7

Sun HW 4

2 of 27

An Array in memory

  • An array is a contiguous block of memory that can be used to hold a fixed number of homogeneous elements.

3 of 27

Arrays in Java

  • Declaration using the [] Modifier:
    • Syntax: base_type[] array_name;
    • Example: int[] income;
  • Accessing Elements using the [] Operator:
    • Syntax: array_name[index]
    • Example: income[5] = 250000;
    • Example: total = income[3];
  • A Reminder About Indexes:
    • 0-based (i.e., the "first" element has an index of 0)

4 of 27

When elements are known up front

  • One can declare an array and assign all of the elements to it using an "array literal" (formally, an array initializer) as follows:
  • char[] course = {'C','S','1','3','9'};
  • int[] age = {18, 21, 65};

One can then assign elements or access elements using the [] operator.

5 of 27

Elements unknown up front

One can declare an array and assign default values to all of the elements to it as follows:

  • char[] course;
  • int[] age;
  • course = new char[5]; \\ Each element is initialized to '\0'
  • age = new int[3]; \\ Each element is initialized to 0

One can then assign elements or access elements using the [] operator.

6 of 27

Elements of Arrays as parameters

  • Actual Parameters:
    • Syntax: array_name[index]
    • Example: x = payment(income[0]);
  • Formal Parameters:
    • Can't be array elements

7 of 27

Arrays as parameters

  • Formal Parameters:
    • Syntax: (base_type[] array_name)
    • Example: payment(int[] income)
    • Example: main(String[] args)
  • Actual Parameters:
    • Syntax: (array_name)
    • Example: y = payment(taxableIncome);

8 of 27

Returning an Array

  • Syntax:
    • base_type[] method_name([formal_parameter]...)
  • Example:
    • public int[] schedule(){...}

9 of 27

Attributes and methods

    • Attributes:
      1. length contains the number of elements (and is initialized when memory is allocated)
    • Methods:
      • clone() makes a (shallow) copy

10 of 27

Java vs Python

  • The Functionality:
    • In Python, a List is used to provide this kind of functionality
  • "Literals":
    • In Python, List literals are written using [ and ] (not { and })
  • Length:
    • In Python, the length of a List can be obtained using the len()function

11 of 27

Java vs Python more

  • Special Indexes:
    • In Python, the "index" -1 can be used to work with the last element of the List
    • In Python, a range of indexes can be specified by including a : in the "index" (e.g., data[2:5])
  • Presence:
    • In Python, the in operator can be used to determine if a List contains a particular element
  • Size:
    • In Python, the number of elements in a List can be changed using the append(), insert(), extend(), and remove() methods

12 of 27

PI question Runetone

13 of 27

Streams

  • What Are They:
    • A sequence of bytes with indeterminate length that ends with an END-OF-STREAM character (Ctrl-D in Unix and Ctrl-Z in Windows)
  • Why They Are Used:
    • The way you work with a stream is independent of its channel (e.g., keyboard, console, network connection, storage devices)

14 of 27

Standard Streams

  • What Are They?
    • Streams that are associated with (what used to be) the standard channels for input and output
  • What Does This Mean Now?
    • The terminal window (sometimes called the console) has standard streams associated with it
    • Most IDEs have standard streams associated with one or more windows/panes/views

15 of 27

When are they created

  • When Are They Created?
    • Before main() is called
  • What Are They Named?
    • System.in
    • System.out
    • System.err

16 of 27

Encapsulation of Std Streams

  • Standard Output/Error:
    • System.out and System.err are PrintStream
  • Standard Input:
    • System.in is an InputStream

17 of 27

PrintStream

Unformatted Output:

  • PrintStream.print(java.lang.String)prints the String(i.e., sends it to the stream
  • PrintStream.println(java.lang.String)prints the Stringfollowed by the line separator String (which is "\n" in Linux, "\r" in OSX and "\r\n" in MSW)��An Important Point:� Text sent to an output stream may be buffered� To force text through the buffer use PrintStream.flush()� This is particularly important to be aware of when
  • debugging

18 of 27

Formatting PrintStream

Format Strings:

  • Encapsulated in the Formatter:�Two Approaches to Using Format Strings:
  • Use the String.format(java.lang.String, java.lang.Object...)method to create a formatted Stringand then call print() or println()
  • Use the PrintStream.printf(java.lang.String, java.lang.Object...)convenience method to perform both steps in one call

19 of 27

Format String

  • Components:
    • String literals
    • Format specifiers
  • Format Specifiers:
    • Syntax: %[flags][width][.precision]conversion
  • Conversions:
    • 'b' for a boolean
    • 'c' for a char
    • 'd' for an integer
    • 'e' for a real number in scientific notation
    • 'f' for a real number
    • 's' for a String
  • Flags:
    • '-' for left-justified
    • '+' to always include the sign
    • ' ' to use a space for the sign of a positive number
    • '0' to pad with zeros
    • ',' to use grouping separators
    • '(' to put negative numbers in parentheses

20 of 27

Example

  • import java.io.PrintStream;
  • public class PrintfExample
  • {
  • public static void main(String[] args)
  • {
  • int age, weight;
  • double monday, tuesday, wednesday;
  • age = 27;
  • System.out.printf("%d\n", age);
  • System.out.printf("%10d\n", age);
  • weight = 155;
  • System.out.printf("Prof. B. is %d years old\n", age);
  • System.out.printf("Age: %d\tWeight: %d\n", age, weight);
  • monday = 35.8;
  • tuesday = 0.0;
  • wednesday = -10.2;
  • System.out.println("\nWith No Flags, Width or Precision");
  • System.out.printf("%f\n", monday);
  • System.out.printf("%f\n", tuesday);
  • System.out.printf("%f\n", wednesday);
  • System.out.println("\nWith No Flags");
  • System.out.printf("%5.1f\n", monday);
  • System.out.printf("%5.1f\n", tuesday);
  • System.out.printf("%5.1f\n", wednesday);
  • System.out.println("\nWith + Flags");
  • System.out.printf("%+5.1f\n", monday);
  • System.out.printf("%+5.1f\n", tuesday);
  • System.out.printf("%+5.1f\n", wednesday);
  • }
  • }

21 of 27

InputStream

    • Raw Input:
      1. The read() methods can be used to read one or more bytes
    • An Observation:
      • We don't want to have to work with the binary representation of char, double, or int
    • A Better Approach:
      • "Wrap" the InputStream in a Scanner object and use its next___() methods

22 of 27

Using Scanner object

Important Constructors:

  • Scanner(java.io.InputStream)

Some Relevant Methods:

  • Scanner.useDelimiter(java.lang.String) �Scanner.hasNextDouble(), Scanner.hasNextInt, Scanner.hasNextLine()�

23 of 27

Scanner Example

  • import java.util.Scanner;
  • public class ScannerExample
  • {
  • public static void main(String[] args)
  • {
  • int age, weight;
  • double salary;
  • Scanner keyboard;
  • String line, name;
  • String[] parts;
  • keyboard = new Scanner(System.in);
  • System.out.print("Name: ");
  • name = keyboard.nextLine();
  • System.out.print("Salary: ");
  • salary = keyboard.nextDouble();
  • keyboard.nextLine(); // Consume the end-of-line character
  • System.out.print("Phone number (###-###-####): ");
  • line = keyboard.nextLine();
  • System.out.print("Age Weight (# #): ");
  • age = keyboard.nextInt();
  • weight = keyboard.nextInt();
  • keyboard.close();
  • }
  • }

24 of 27

Issue when using Scanner

  • import java.util.Scanner;
  • public class ScannerInconvenienceExample
  • {
  • public static void main(String[] args)
  • {
  • int age;
  • Scanner keyboard;
  • String name;
  • keyboard = new Scanner(System.in);
  • // If you run this program you won't be able to enter your
  • // name because the return you enter after your age will
  • // be considered the "next line"
  • System.out.print("Enter your age: ");
  • age = keyboard.nextInt();
  • System.out.print("Enter your name: ");
  • name = keyboard.nextLine();
  • keyboard.close();
  • }
  • }

25 of 27

Scanner issue/ “bug”

  • The Issue:
    • The methods that read "up to" a delimiter do not consume newline characters
  • A "Work Around":
    • Invoke nextLine() immediately after invoking one of these methods

26 of 27

New approach

  • A Recent Addition:
    • A Console object can be retrieved using the System.console() method and it has both readLine() and printf() methods
  • Problems with this Approach:
    • The console() method returns null in IDEs
    • The streams can't be re-directed within a program making it inappropriate for many testing environments

27 of 27

  • Acknowledgements

Parts of this activity are based on materials developed by David Bernstein.

</end>