uzh - 2. primitive types, strings, and console i/o · 2016. 6. 23. · 1 2. primitive types,...

46
1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch 2 Objectives become familiar with Java primitive types (numbers, characters, etc.) learn about assignment statements and expressions learn about strings become familiar with classes, methods, and objects 3 © 2005 W. Savitch, Pearson Prentice Hall Objectives, cont. learn about simple keyboard input and screen output learn about windows-based input and output using the JOptionPane class

Upload: others

Post on 13-Mar-2021

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

1

2. Primitive Types, Strings, and Console I/O

Prof. Dr. Harald Gall Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch

2

Objectives

n  become familiar with Java primitive types (numbers, characters, etc.)

n  learn about assignment statements and expressions

n  learn about strings n  become familiar with classes, methods, and

objects

3 © 2005 W. Savitch, Pearson Prentice Hall

Objectives, cont.

n  learn about simple keyboard input and screen output

n  learn about windows-based input and output using the JOptionPane class

Page 2: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

2

4 © 2005 W. Savitch, Pearson Prentice Hall

Outline

n  Primitive Types and Expressions n  The Class String n  Keyboard and Screen I/O n  Documentation and Style

5 © 2005 W. Savitch, Pearson Prentice Hall

Prerequisite

n  familiarity with the notions of class, method, and object

Primitive Types and Expressions: Outline

Variables Java Identifiers Primitive Types Assignment Statements Specialized Assignment Operators Simple Screen Output Simple Input

Page 3: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

3

Primitive Types and Expressions: Outline, cont.

Number Constants Assignment Compatibilities Type Casting Arithmetic Operations Parentheses and Precedence Rules Increment and Decrement Operators

8 © 2005 W. Savitch, Pearson Prentice Hall

Variables and Values

n  Variables store data such as numbers and letters n  They are places to store data n  They are implemented as memory locations

n  The data stored by a variable is called its value n  The value is stored in the memory location

n  Its value can be changed

9 © 2005 W. Savitch, Pearson Prentice Hall

Variables and Values, cont.

n  Example n  class EggBasket

Page 4: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

4

10 © 2005 W. Savitch, Pearson Prentice Hall

Variables and Values, cont.

n  variables numberOfBaskets

eggsPerBasket

totalEggs

n  assigning values eggsPerBasket = 6;

eggsPerBasket = eggsPerBasket - 2;

11 © 2005 W. Savitch, Pearson Prentice Hall

Naming and Declaring Variables

n  Choose names that are helpful such as count or speed, but not c or s

n  When you declare a variable, you provide its name and type int numberOfBaskets,eggsPerBasket;

n  A variable’s type determines what kinds of values it can hold (int, double, char, etc.)

n  A variable must be declared before it is used

12 © 2005 W. Savitch, Pearson Prentice Hall

Syntax and Examples

n  syntax type variable_1, variable_2, …;

(variable_1 is a generic variable called a syntactic variable)

n  examples int styleChoice, numberOfChecks; double balance, interestRate;

char jointOrIndividual;

Page 5: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

5

13 © 2005 W. Savitch, Pearson Prentice Hall

Types in Java

n  A class type is used for a class of objects and has both data and methods. n  “Frankie goes to Hollywood” is a value of

class type String

n  A primitive type is used for simple, nondecomposable values such as an individual number or individual character. n  int, double, and char are primitive types.

14 © 2005 W. Savitch, Pearson Prentice Hall

Naming Conventions

n  Class types begin with an uppercase letter (e.g. String).

n  Primitive types begin with a lowercase letter (e.g. int).

n  Variables of both class and primitive types begin with a lowercase letters (e.g. myName, myBalance). n  Multiword names are “punctuated” using uppercase

letters (= CamelCase).

15 © 2005 W. Savitch, Pearson Prentice Hall

Where to Declare Variables

n  Declare a variable n  just before it is used or n  at the beginning of the section of your program that

is enclosed in {}.

public static void main(String[] args) { /* declare variables here */

int numberOfBaskets, eggsPerBasket, totalEggs;

Page 6: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

6

16 © 2005 W. Savitch, Pearson Prentice Hall

Java Identifiers

n  An identifier is a name, such as the name of a variable

n  Identifiers may contain only n  letters n  digits (0 through 9) n  the underscore character (_) n  and the dollar sign symbol ($) which has a special

meaning but the first character cannot be a digit

17 © 2005 W. Savitch, Pearson Prentice Hall

Java Identifiers, cont.

n  identifiers may not contain any spaces, dots (.), asterisks (*), or other characters:

7-11 netscape.com util.* (not allowed)

n  Identifiers can be arbitrarily long n  Since Java is case sensitive, stuff, Stuff, and STUFF

are different identifiers

18 © 2005 W. Savitch, Pearson Prentice Hall

Grammatik / EBNF

n  Grammatik: Regeln zur exakten Definition einer "korrekten" Schreibweise n  Missverständnisse ausschließen: Grammatik formal verfassen n  Kein Interpretationsspielraum: Text ist entweder "richtig" oder "falsch"

n  Gegensatz zu natürlichen Sprachen: n  keine formale Grammatik, keine exakte Abgrenzung richtig/falsch

n  Populäre Schreibweise: "Extended Backus-Naur Form" (EBNF) n  Liste von Produktionen = Ersetzungsregeln・ n  Jede Produktion:

n  Linke Seite = Platzhalter, Variable, Nichtterminal n  Rechte Seite = Folge von Symbolen, durch die die linke Seite ersetzt

werden kann n  Symbol: Nichtterminal oder Terminal, letzteres kann nicht mehr

ersetzt werden

Page 7: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

7

19 © 2005 W. Savitch, Pearson Prentice Hall

Metasymbole der EBNF

Beispiel: Grammatik für ganzzahlige Numerale: sign ⇒ “+” | “-” digit ⇒ “0” | ... | “9” numeral ⇒ [sign] digit+

⇒ trennt linke und rechte Seite

(...) gruppiert Symbolfolgen

[...] Option, geklammerte Symbole dürfen auch weggelassen werden

* beliebige Wiederholung (auch null-mal)

+ ein- oder mehrmalige Wiederholung

| trennt Alternativen

20 © 2005 W. Savitch, Pearson Prentice Hall

Keywords or Reserved Words

n  Words such as if are called keywords or reserved words and have special, predefined meanings

n  Keywords cannot be used as identifiers n  See Appendix 1 for a complete list of Java

keywords n  other keywords: int, public, class

21 © 2005 W. Savitch, Pearson Prentice Hall

Primitive Types

n  four integer types: byte, short, int, and long n  int is most common

n  two floating-point types: float and double n  double is more common

n  one character type: char n  one boolean type: boolean

Page 8: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

8

22 © 2005 W. Savitch, Pearson Prentice Hall

Primitive Types, cont.

23 © 2005 W. Savitch, Pearson Prentice Hall

Examples of Primitive Values

n  integer types 0 -1 365 12000

n  floating-point types 0.99 -22.8 3.14159 5.0

n  character type ‘a’ ‘A’ ‘#’ ‘ ‘

n  boolean type true false

24 © 2005 W. Savitch, Pearson Prentice Hall

Assignment Statements

n  An assignment statement is used to assign a value to a variable. answer = 42;

n  The “equal sign” is called the assignment operator.

n  We say: “The variable named answer is assigned a value of 42,” or more simply, “answer is assigned 42.”

Page 9: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

9

25 © 2005 W. Savitch, Pearson Prentice Hall

Assignment Statements, cont.

n  Syntax n  variable = expression

n  EBNF n  assignment ⇒ identifier "=” expression ";”

n  where expression can be another variable, a literal or constant (such as a number), or something more complicated which combines variables and literals using operators (such as + and -)

26 © 2005 W. Savitch, Pearson Prentice Hall

Assignment Examples

amount = 3.99; firstInitial = ‘W’;

score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2;

27 © 2005 W. Savitch, Pearson Prentice Hall

Assignment Evaluation

n  The expression on the right-hand side of the assignment operator (=) is evaluated first.

n  The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2;

Page 10: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

10

28 © 2005 W. Savitch, Pearson Prentice Hall

Specialized Assignment Operators

n  Assignment operators can be combined with arithmetic operators (including -, *, /, and %). amount = amount + 5; can be written as amount += 5; yielding the same results.

29 © 2005 W. Savitch, Pearson Prentice Hall

Simple Screen Output

System.out.println(“The count is “ + count);

outputs the string literal “The count is “ followed by the current value of the variable count.

30 © 2005 W. Savitch, Pearson Prentice Hall

Simple Input

n  Sometimes the data needed for a computation are obtained from the user at run time.

n  Keyboard input requires import java.util.* at the beginning of the file.

Page 11: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

11

31 © 2005 W. Savitch, Pearson Prentice Hall

Simple Input, cont.

n  Data can be entered from the keyboard using Scanner keyboard =

new Scanner(System.in);

followed, for example, by

eggsPerBasket = keyboard.nextInt();

which reads one int value from the keyboard and assigns it to eggsPerBasket

32 © 2005 W. Savitch, Pearson Prentice Hall

Simple Input, cont. n  class EggBasket2

33 © 2005 W. Savitch, Pearson Prentice Hall

Number Constants

n  Literal expressions such as 2, 3.7, or ‘y’ are called constants

n  Integer constants can be preceded by a + or - sign, but cannot contain commas

n  Floating-point constants can be written n  with digits after a decimal point or n  using e notation, also called scientific notation or floating-point

notation n  Examples

n  865000000.0 can be written as 8.65e8 n  0.000483 can be written as 4.83e-4

n  The number in front of the e does not need to contain a decimal point

Page 12: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

12

34 © 2005 W. Savitch, Pearson Prentice Hall

Assignment Compatibilities

n  Java is said to be strongly typed n  You can’t, for example, assign a floating point value

to a variable declared to store an integer. n  Sometimes conversions between numbers are

possible. double doubleVariable; doubleVariable = 7; is possible even if doubleVariable is of type double, for example.

35 © 2005 W. Savitch, Pearson Prentice Hall

Assignment Compatibilities cont.

n  A value of one type can be assigned to a variable of any type further to the right

byte --> short --> int --> long --> float --> double but not to a variable of any type further to the left.

n  You can assign a value of type char to a variable of type int

36 © 2005 W. Savitch, Pearson Prentice Hall

Floatingpoint

n  "Gleitkommazahlen", "Fliesskommazahlen” n  Bezeichnung mit reserviertem Wort "double", gleichberechtigt zu

"int” fpnumeral ⇒ [sign] digit+ "." digit* [exponent] [doublesuffix] fpnumeral ⇒ [sign] "." digit+ [exponent] [doublesuffix] fpnumeral ⇒ [sign] digit+ exponent [doublesuffix] fpnumeral ⇒ [sign] digit+ doublesuffix exponent ⇒ ("E” | "e") [sign] digit+ doublesuffix ⇒ "D” | "d”

n  Typ einer Variable bei der Definition festgelegt:

int i; double d; final double pi = 3.1415926

Page 13: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

13

37 © 2005 W. Savitch, Pearson Prentice Hall

int vs. double

n  Floatingpoint-Arithmetik rechnerisch viel genauer, wozu noch ganzzahlige Arithmetik?

n  int-Arithmetik wichtig weil... n  int ist schneller n  double braucht mehr Platz n  int immer exakt, double nicht

Beispiel: n  (1.0/x)*x - 1.0 liefert nicht immer null

n  int wenn möglich n  double wenn es die Aufgabe erfordert

38 © 2005 W. Savitch, Pearson Prentice Hall

•  Automatische Typumwandlung int→double: "implizite Typkonversion” Keine implizite Typkonversionen double→int

Implizite Typkonversion int→double n  Zwei Operanden gleichen Typs:

n  Operandentyp = Ergebnistyp

n  Gemischte Operandentypen: n  double ist Ergebnistyp

n  1 + 2 → 3 (int) n  1.0 + 2 → 3.0 (double)

n  1 + 2.0 → 3.0 (double)

n  1.0 + 2.0 → 3.0 (double)

39 © 2005 W. Savitch, Pearson Prentice Hall

Legale Konvertierungen

byte short int

char

long

float double

... Konvertierung ohne Informationsverlust ... Konvertierung mit möglichem Informationsverlust

Page 14: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

14

40 © 2005 W. Savitch, Pearson Prentice Hall

Implizite Konvertierungen

n  Werden 2 Werte durch einen binären Operator verknüpft: n  Ist einer der Operanden

n  ein double, so wird der andere zu double konvertiert, n  ein float, so wird der andere zu float konvertiert, n  ein long, so wird der andere zu long konvertiert n  anderenfalls beide zu int konvertiert werden

n  bevor die Operation ausgeführt wird (implicit type conversion)

41 © 2005 W. Savitch, Pearson Prentice Hall

float and double Literale

n  Scientific notation: n  98.6, 986e-1, 0.986e2, 9.86e1

n  Um float von double zu unterscheiden, muss der Literal ein “f” am Schluss stehen haben n  3.14159f

n  Das gleiche gilt für double Werte. Um sie von int Werten zu unterscheiden hängt man ein “d” an.n  98d

42 © 2005 W. Savitch, Pearson Prentice Hall

Benutzung von float und double

int j = 12223334444;float x = 122233334444.0f;

System.out.println("j = " + j);System.out.println("x = " + x);j = j + 1;x = x + 1.0;System.out.println("j = " + j);System.out.println("x = " + x);

j = 1222333444x = 1.22233344E9j = 1222333445x = 1.22233344E9

Output:

Page 15: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

15

43 © 2005 W. Savitch, Pearson Prentice Hall

Implementation public double convertFeetToMeters(double feet) {

return feet * 0.3048; }

n  Besser: return feet * METERSPERFOOT;

public static final double METERSPERFOOT = 0.3048;

44 © 2005 W. Savitch, Pearson Prentice Hall

Type Casting

n  A type cast temporarily changes the value of a variable from the declared type to some other type.

n  For example, double distance; distance = 9.0; int points; points = (int)distance;

(illegal without (int))

45 © 2005 W. Savitch, Pearson Prentice Hall

Type Casting, cont.

n  The value of (int)distance is 9, but the value of distance, both before and after the cast, is 9.0.

n  Any nonzero value to the right of the decimal point is truncated rather than rounded.

double distance;

distance = 9.99; int points;

points = (int)distance;

Page 16: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

16

46 © 2005 W. Savitch, Pearson Prentice Hall

Initializing Variables

n  A variable that has been declared, but no yet given a value is said to be uninitialized.

n  Uninitialized class variables have the value null.

n  Uninitialized primitive variables may have a default value.

n  It’s good practice not to rely on a default value.

47 © 2005 W. Savitch, Pearson Prentice Hall

Initializing Variables, cont.

n  To protect against an uninitialized variable (and to keep the compiler happy), assign a value at the time the variable is declared.

n  Examples: int count = 0; char grade = ‘A’;

48 © 2005 W. Savitch, Pearson Prentice Hall

Initializing Variables, cont.

n  Syntax type variable_1 = expression_1, variable_2 = expression_2, …;

n  Example int number = 0, increment = 1;

Page 17: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

17

49 © 2005 W. Savitch, Pearson Prentice Hall

Imprecision in Floating-Point Numbers n  Floating-point numbers often are only approximations

since they are stored with a finite number of bits. n  Hence 1.0/3.0 is slight less than 1/3. n  1.0/3.0 + 1.0/3.0 + 1.0/3.0 is less than 1.

50 © 2005 W. Savitch, Pearson Prentice Hall

Arithmetic Operations

n  Arithmetic expressions can be formed using the +, -, *, and / operators together with variables or numbers referred to as operands. n  When both operands are of the same type, the result is of that

type. n  When one of the operands is a floating-point type and the other

is an integer, the result is a floating point type.

51 © 2005 W. Savitch, Pearson Prentice Hall

Arithmetic Operations, cont.

n  Example If hoursWorked is an int to which the value 40 has been assigned, and payRate is a double to which 8.25 has been assigned

hoursWorked * payRate

is a double with a value of 330.0

Page 18: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

18

52 © 2005 W. Savitch, Pearson Prentice Hall

Arithmetic Operations, cont.

n  Expressions with two or more operators can be viewed as a series of steps, each involving only two operands. n  The result of one step produces one of the operands to be

used in the next step.

n  example balance + (balance * rate)

53 © 2005 W. Savitch, Pearson Prentice Hall

Arithmetic Operations, cont.

n  if at least one of the operands is a floating-point type and the rest are integers, the result will be a floating point type.

n  The result is the rightmost type from the following list that occurs in the expression. byte --> short --> int --> long --> float --> double

54 © 2005 W. Savitch, Pearson Prentice Hall

The Division Operator

n  The division operator (/) behaves as expected if one of the operands is a floating-point type.

n  When both operands are integer types, the result is truncated, not rounded. n  Hence, 99/100 has a value of 0.

Page 19: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

19

55 © 2005 W. Savitch, Pearson Prentice Hall

The mod Operator

n  The mod (%) operator is used with operators of integer type to obtain the remainder after integer division

n  14 divided by 4 is 3 with a remainder of 2 n  Hence, 14 % 4 is equal to 2

n  The mod operator has many uses, including n  determining if an integer is odd or even n  determining if one integer is evenly divisible by

another integer

56 © 2005 W. Savitch, Pearson Prentice Hall

Parentheses and Precedence

n  Parentheses can communicate the order in which arithmetic operations are performed

n  examples: (cost + tax) * discount cost + (tax * discount)

n  Without parentheses, an expressions is evaluated according to the rules of precedence.

57 © 2005 W. Savitch, Pearson Prentice Hall

Precedence Rules

Page 20: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

20

58 © 2005 W. Savitch, Pearson Prentice Hall

Precedence Rules, cont.

n  The binary arithmetic operators *, /, and %, have lower precedence than the unary operators +, -, ++, --, and !, but have higher precedence than the binary arithmetic operators + and -.

n  When binary operators have equal precedence, the operator on the left acts before the operator(s) on the right.

59 © 2005 W. Savitch, Pearson Prentice Hall

Precedence Rules, cont.

n  When unary operators have equal precedence, the operator on the right acts before the operation(s) on the left.

n  Even when parentheses are not needed, they can be used to make the code clearer. balance + (interestRate * balance)

n  Spaces also make code clearer balance + interestRate*balance

but spaces do not dictate precedence.

60 © 2005 W. Savitch, Pearson Prentice Hall

Sample Expressions

Page 21: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

21

61 © 2005 W. Savitch, Pearson Prentice Hall

Case Study: Vending Machine Change

n  requirements n  The user enters an amount between 1 cent and 99

cents. n  The program determines a combination of coins

equal to that amount. n  For example, 55 cents can be two quarters and one

nickel.

62 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

n  sample dialog Enter a whole number from 1 to 99.

The machine will determine a combination of coins.

87 cents in coins: 3 quarters 1 dime

0 nickels

2 pennies

63 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

n  variables needed int amount, quarters, dimes, nickels, pennies;

Page 22: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

22

64 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

n  Algorithm - first version:

1.  Read the amount. 2.  Find the maximum number of quarters in the amount. 3.  Subtract the value of the quarters from the amount. 4.  Repeat the last two steps for dimes, nickels, and pennies. 5.  Print the original amount and the quantities of each coin.

65 © 2005 W. Savitch, Pearson Prentice Hall

Case Study,cont.

n  The algorithm doesn’t work properly, because the original amount is changed by the intermediate steps. n  The original value of amount is lost.

n  Change the list of variables int amount, originalAmount, quarters, dimes, nickles, pennies;

n  and update the algorithm

66 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

1.  Read the amount. 2.  Make a copy of the amount. 3.  Find the maximum number of quarters in the

amount. 4.  Subtract the value of the quarters from the amount. 5.  Repeat the last two steps for dimes, nickels, and

pennies. 6.  Print the original amount and the quantities of each

coin.

Page 23: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

23

67 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

n  Write Java code that implements the algorithm written in pseudo code

68 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

n  How do we determine the number of quarters (or dimes, nickels, or pennies) in an amount?

n  There are 2 quarters in 55 cents, but there are also 2 quarters in 65 cents.

n  That’s because 55 / 2 = 2 and 65 / 25 = 2

69 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

n  How do we determine the remaining amount?

n  The remaining amount can be determined using the mod operator 55 % 25 = 5 and 65 % 25 = 15

n  and similarly for dimes and nickels n  Pennies are simply amount % 5

Page 24: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

24

70 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont. n  class ChangeMaker

71 © 2005 W. Savitch, Pearson Prentice Hall

Case Study, cont.

n  The program should be tested with several different amounts.

n  Test with values that give zero values for each possible coin denomination.

n  Test with amounts close to n  extreme values such as 0, 1, 98 and 99 n  coin denominations, such as 24, 25, and 26.

72 © 2005 W. Savitch, Pearson Prentice Hall

Increment (and Decrement) Operators n  used to increase (or decrease) the value of a variable

by 1 n  easy to use, important to recognize n  the increment operator

count++ or ++count

n  the decrement operator count-- or --count

Page 25: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

25

73 © 2005 W. Savitch, Pearson Prentice Hall

Increment (and Decrement) Operators

n  equivalent operations n  count++; n  ++count; n  count = count + 1;

n  count--;

n  --count; n  count = count - 1;

74 © 2005 W. Savitch, Pearson Prentice Hall

Increment (and Decrement) Operators in Expressions n  after executing

int m = 4;

int result = 3 * (++m)

result has a value of 15 and m has value 5 n  after executing

int m = 4; int result = 3 * (m++)

result has a value of 12 and m has value 5

75 © 2005 W. Savitch, Pearson Prentice Hall

The Class String

n  We’ve used constants of type String already. “Enter a whole number from 1 to 99.”

n  A value of type String is a sequence of characters treated as a single item.

Page 26: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

26

76 © 2005 W. Savitch, Pearson Prentice Hall

Declaring and Printing Strings

n  declaring String greeting; greeting = “Hello!”;

n  or String greeting = “Hello!”;

n  or String greeting = new String(“Hello!”);

n  printing System.out.println(greeting);

77 © 2005 W. Savitch, Pearson Prentice Hall

Concatenation of Strings

n  Two strings are concatenated using the + operator. String greeting = “Hello”;

String sentence;

sentence = greeting + “ officer”;

System.out.println(sentence);

n  Any number of strings can be concatenated using the + operator.

78 © 2005 W. Savitch, Pearson Prentice Hall

Concatenating Strings and Integers

String solution; solution = “The answer is“ + 42;

System.out.println (solution);

> The answer is 42

Page 27: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

27

79 © 2005 W. Savitch, Pearson Prentice Hall

Classes

n  A class is a type used to produce objects. n  An object is an entity that stores data and can

take actions defined by methods. n  An object of the String class stores data

consisting of a sequence of characters. n  The length() method returns the number of

characters in a particular String object. int howMany = solution.length()

80 © 2005 W. Savitch, Pearson Prentice Hall

Objects, Methods, and Data

n  Objects within a class n  have the same methods n  have the same kind(s) of data but the data can have different

values.

n  Primitive types have values, but no methods.

81 © 2005 W. Savitch, Pearson Prentice Hall

String Methods

Page 28: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

28

82 © 2005 W. Savitch, Pearson Prentice Hall

The Method length()

n  The method length() returns an int.

n  You can use a call to method length() anywhere an int can be used. int count = solution.length();

System.out.println(solution.length());

count = solution.length() + 3;

83 © 2005 W. Savitch, Pearson Prentice Hall

Positions in a String

n  positions start with 0, not 1. n  The ‘J’ in “Java is fun.” is in position 0

84 © 2005 W. Savitch, Pearson Prentice Hall

•  A position is referred to an an index. –  The ‘f’ in “Java is fun.” is at index 8.

Positions in a String, cont.

Page 29: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

29

85 © 2005 W. Savitch, Pearson Prentice Hall

(Not) Changing String Objects

n  No methods allow you to change the value of a String object.

n  But you can change the value of a String variable.

value of pause String pause = “ Hmm “; Hmm pause = pause.trim(); Hmm pause = pause + “mmm!”; Hmmmmm pause = “Ahhh”; Ahhh

86 © 2005 W. Savitch, Pearson Prentice Hall

Using the String Class n  class StringDemo

87 © 2005 W. Savitch, Pearson Prentice Hall

Escape Characters

n  How would you print “Java” refers to a language.?

n  The compiler needs to be told that the quotation marks (“) do not signal the start or end of a string, but instead are to be printed. System.out.println(

“\”Java\” refers to a language.”);

Page 30: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

30

88 © 2005 W. Savitch, Pearson Prentice Hall

Escape Characters

n  Each escape sequence is a single character even though it is written with two symbols.

89 © 2005 W. Savitch, Pearson Prentice Hall

Examples

System.out.println(“abc\\def”); abc\def System.out.println(“new\nline”);

new line char singleQuote = ‘\’’;

System.out.println(singleQuote);

90 © 2005 W. Savitch, Pearson Prentice Hall

The Unicode Character Set

n  Most programming languages use the ASCII character set.

n  Java uses the Unicode character set which includes the ASCII character set.

n  The Unicode character set includes characters from many different alphabets (but you probably won’t use them).

Page 31: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

31

Keyboard and Screen I/O: Outline

Screen Output Keyboard Input

92 © 2005 W. Savitch, Pearson Prentice Hall

Screen Output

n  We’ve seen several examples of screen output already.

n  System.out is an object that is part of Java. n  println() is one of the methods available to the

System.out object.

93 © 2005 W. Savitch, Pearson Prentice Hall

Screen Output, cont.

n  The concatenation operator (+) is useful when everything does not fit on one line. System.out.println(“When everything “ +

“does not fit on one line, use the” + “ concatenation operator (/’+/’)”);

n  Do not break the line except immediately before or after the concatenation operator (+).

Page 32: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

32

94 © 2005 W. Savitch, Pearson Prentice Hall

Screen Output, cont.

n  Alternatively, use print() System.out.print(“When everything “);

System.out.print(“does not fit on “);

System.out.print(“one line, use the “);

System.out.print(“\”print\” ”);

System.out.println(“statement”);

ending with a println().

95 © 2005 W. Savitch, Pearson Prentice Hall

Screen Output, cont.

n  syntax System.out.println(output_1 + output_2 + … +

output_n);!

n  example System.out.println (1967 + “ “ + “Oldsmobile” + “ “ +

442);

1967 Oldsmobile 442

96 © 2005 W. Savitch, Pearson Prentice Hall

Keyboard Input

n  Java 5.0 has reasonable facilities for handling keyboard input.

n  These facilities are provided by the Scanner class in the java.util package. n  A package is a library of classes.

Page 33: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

33

97 © 2005 W. Savitch, Pearson Prentice Hall

Using the Scanner Class

n  Near the beginning of your program, insert import java.util.*

n  Create an object of the Scanner class Scanner keyboard =

new Scanner (System.in)

n  Read data (an int or a double, for example) int n1 = keyboard.nextInt();

double d1 = keyboard.nextDouble();

98 © 2005 W. Savitch, Pearson Prentice Hall

Keyboard Input Demonstration n  class ScannerDemo

99 © 2005 W. Savitch, Pearson Prentice Hall

Some Scanner Class Methods

n  Syntax Int_Variable = Object_Name.nextInt(); Double_Variable = Object_Name.nextDouble(); String_Variable = Object_Name.next(); String_Variable = Object_Name.nextLine();

Page 34: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

34

100 © 2005 W. Savitch, Pearson Prentice Hall

Scanner Class Methods

n  examples int count = keyboard.nextInt(); double distance = keyboard.nextDouble();

String word = keyboard.next();

String wholeLine = keyboard.nextLine();

n  Remember to prompt the user for input, e.g. System.out.print(“Enter an integer: “);

101 © 2005 W. Savitch, Pearson Prentice Hall

nextLine()Method Caution

n  The nextLine() method reads the remainder of the current line, even if it is empty.

102 © 2005 W. Savitch, Pearson Prentice Hall

nextLine()Method Caution, cont.

n  example int n;

String s1, s2;

n = keyboard.nextInt();

s1 = keyboard.nextLine(); s2 = keyboard.nextLine();

5440 or bust

n is set to 5440

but s1 is set to the empty string.

Page 35: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

35

103 © 2005 W. Savitch, Pearson Prentice Hall

The Empty String

n  A string can have any number of characters, including zero.

n  The string with zero characters is called the empty string.

n  The empty string is useful and can be created in many ways including String s3 = “”;

104 © 2005 W. Savitch, Pearson Prentice Hall

(optional) Other Input Delimiters

n  Almost any combination of characters and strings can be used to separate keyboard input.

n  to change the delimiter to “##” keyboard2.useDelimiter(“##”);

n  whitespace will no longer be a delimiter for keyboard2 input

105 © 2005 W. Savitch, Pearson Prentice Hall

(optional) Other Input Delimiters, cont. n  class DelimitersDemo

Page 36: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

36

106 © 2005 W. Savitch, Pearson Prentice Hall

Documentation and Style: Outline

n  Meaningful Names n  Self-Documentation and Comments n  Indentation n  Named Constants

107 © 2005 W. Savitch, Pearson Prentice Hall

Documentation and Style

n  Most programs are modified over time to respond to new requirements.

n  Programs which are easy to read and understand are easy to modify.

n  Even if it will be used only once, you have to read it in order to debug it .

108 © 2005 W. Savitch, Pearson Prentice Hall

Meaningful Names for Variables

n  A variable’s name should suggest its use. n  Observe conventions in choosing names for

variables. n  Use only letters and digits. n  “Punctuate” using uppercase letters at word

boundaries (e.g. taxRate). n  Start variables with lowercase letters. n  Start class names with uppercase letters.

Page 37: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

37

109 © 2005 W. Savitch, Pearson Prentice Hall

Documentation and Comments

n  The best programs are self-documenting. n  clean style n  well-chosen names

n  Comments are written into a program as needed explain the program. n  They are useful to the programmer, but they are ignored by the

compiler.

110 © 2005 W. Savitch, Pearson Prentice Hall

Comments

n  A comment can begin with //. n  Everything after these symbols and to the end of the line is

treated as a comment and is ignored by the compiler. double radius; //in centimeters

111 © 2005 W. Savitch, Pearson Prentice Hall

Comments, cont.

n  A comment can begin with /* and end with */ n  Everything between these symbols is treated as a comment

and is ignored by the compiler. /* the simplex method is used to

calculate the answer*/

Page 38: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

38

112 © 2005 W. Savitch, Pearson Prentice Hall

Comments, cont.

n  A javadoc comment, begins with /** and ends with */. n  It can be extracted automatically from Java software. /** method change requires the number of coins to be

nonnegative */

113 © 2005 W. Savitch, Pearson Prentice Hall

When to Use Comments

n  Begin each program file with an explanatory comment n  what the program does n  the name of the author n  contact information for the author n  date of the last modification.

n  Provide only those comments which the expected reader of the program file will need in order to understand it.

114 © 2005 W. Savitch, Pearson Prentice Hall

Comments Example n  class CircleCalculation

Page 39: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

39

115 © 2005 W. Savitch, Pearson Prentice Hall

Indentation

n  Indentation should communicate nesting clearly. n  I good choice is four spaces for each level of

indentation. n  Indentation should be consistent. n  Indentation should be used for second and subsequent

lines of statements which do not fit on a single line.

116 © 2005 W. Savitch, Pearson Prentice Hall

Indentation, cont.

n  Indentation does not change the behavior of the program.

n  Improper indentation can miscommunicate the behavior of the program.

117 © 2005 W. Savitch, Pearson Prentice Hall

Named Constants

n  To avoid confusion, always name constants (and variables). circumference = PI * radius; is clearer than circumference = 3.14159 * 6.023;

n  Place constants near the beginning of the program.

Page 40: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

40

118 © 2005 W. Savitch, Pearson Prentice Hall

Named Constants, cont.

n  Once the value of a constant is set (or changed by an editor), it can be used (or reflected) throughout the program. public static final double INTEREST_RATE = 6.65;

n  If a literal (such as 6.65) is used instead, every occurrence must be changed, with the risk than another literal with the same value might be changed unintentionally.

119 © 2005 W. Savitch, Pearson Prentice Hall

Declaring Constants

n  syntax public static final Variable_Type = Constant;

n  examples public static final double PI = 3.14159;

public static final String MOTTO = “The customer is always right.”;

n  By convention, uppercase letters are used for constants.

120 © 2005 W. Savitch, Pearson Prentice Hall

Named Constants n  class CircleCalculation2

Page 41: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

41

121 © 2005 W. Savitch, Pearson Prentice Hall

(optional) Graphics Supplement: Outline n  Style Rules Applied to a Graphics Applet n  JOptionPane

n  Inputting Numeric Types n  Multi-Line Output Windows

122 © 2005 W. Savitch, Pearson Prentice Hall

Style Rules Applied to a Graphics Applet n  class HappyFace

123

Style Rules Applied to a Graphics Applet, cont.

n  Named constants makes it easier to find values. n  Comments and named constants make

changing the code much easier. n  Named constants protect against changing the

wrong value.

© 2005 W. Savitch, Pearson Prentice Hall

Page 42: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

42

124 © 2005 W. Savitch, Pearson Prentice Hall

JOptionPane n  class JOptionPaneDemo

125 © 2005 W. Savitch, Pearson Prentice Hall

JOptionPane, cont.

n  JOptionPane can be used to construct windows that interact with the user.

n  The JOptionPane class is imported by import javax.swing.*;

n  The JOptionPane class produces windows for obtaining input or displaying output.

126 © 2005 W. Savitch, Pearson Prentice Hall

JOptionPane, cont.

n  Use showInputDialog() for input . n  Only string values can be input. n  To convert an input value from a string to an integer use

the parseInt() method from the Integer class, use appleCount = Integer.parseInt(appleString);

Page 43: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

43

127 © 2005 W. Savitch, Pearson Prentice Hall

JOptionPane, cont.

n  Output is displayed using the showMessageDialog method. JOptionPane.showMessageDialog(null, “The total number

of fruits = “ + totalFruitCount);

128 © 2005 W. Savitch, Pearson Prentice Hall

JOptionPane, cont.

n  syntax n  input

String_Variable = JOptionPane.showInputDialogue(String_Expression);

n  output JOptionPane.showMessageDialog(null, String_Expression);

n  System.exit(0) ends the program.

129 © 2005 W. Savitch, Pearson Prentice Hall

JOptionPane Cautions

n  If the input is not in the correct format, the program will crash.

n  If you omit the last line (System.exit(0)), the program will not end, even when the OK button in the output window is clicked.

n  Always label any output.

Page 44: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

44

130 © 2005 W. Savitch, Pearson Prentice Hall

Inputting Numeric Types n  JOptionPane.showInput Dialog can be used to

input any of the numeric types. n  Simply convert the input string to the

appropriate numeric type.

131 © 2005 W. Savitch, Pearson Prentice Hall

Multi-Line Output Windows

n  To output multiple lines using the method JOptionPane.showMessage Dialog, insert the new line character ‘\n’ into the string used as the second argument. OptionPane.showMessageDialog(null,

“The number of apples\n” +

“plus the number of oranges\n” + “is equal to “ + totalFruit);

132 © 2005 W. Savitch, Pearson Prentice Hall

Multi-Line Output Windows, cont.

Page 45: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

45

133 © 2005 W. Savitch, Pearson Prentice Hall

Programming Example n  class ChangeMakerWindow

134 © 2005 W. Savitch, Pearson Prentice Hall

Programming Example, cont.

135 © 2005 W. Savitch, Pearson Prentice Hall

Summary

n  You have become familiar with Java primitive types (numbers, characters, etc.).

n  You have learned about assignment statements and expressions.

n  You have learned about stings. n  You have become familiar with classes,

methods, and objects.

Page 46: UZH - 2. Primitive Types, Strings, and Console I/O · 2016. 6. 23. · 1 2. Primitive Types, Strings, and Console I/O Prof. Dr. Harald Gall Institut für Informatik Universität Zürich

46

136 © 2005 W. Savitch, Pearson Prentice Hall

Summary, cont.

n  You have learned about simple keyboard input and screen output.

n  (optional) You have learned about windows-based input and output using the JOptionPane class.