CDIT Java01 00_Introduction to Java

84
Part 1: Java as an Object-oriented Programming Language 00. Introduction to Java STP Curriculum – Java course

description

giói thiệu tổng quan về java bằng tiếng anh

Transcript of CDIT Java01 00_Introduction to Java

Page 1: CDIT Java01 00_Introduction to Java

Part 1: Java as an Object-oriented

Programming Language

00. Introduction to Java

STP Curriculum – Java course

Page 2: CDIT Java01 00_Introduction to Java

Java History

• James Gosling and Sun Microsystems

• Oak

• Java, May 20, 1995, Sun World

• Hot Java – The first Java-enabled Web browser

• JDK Evolutions

• J2SE, J2ME, and J2EE

13/03/2015 2

Page 3: CDIT Java01 00_Introduction to Java

JDK Editions

• Java Standard Edition (J2SE)– J2SE can be used to develop client-side standalone applications or

applets.

• Java Enterprise Edition (J2EE)– J2EE can be used to develop server-side applications such as Java

servlets and Java ServerPages.

• Java Micro Edition (J2ME). – J2ME can be used to develop applications for mobile devices such as

cell phones.

13/03/2015 3

Page 4: CDIT Java01 00_Introduction to Java

Java IDE Tools

• Text Pad

• Net Bean

• EClipse

13/03/2015 4

Page 5: CDIT Java01 00_Introduction to Java

Your first Java program!

public class Hello {

public static void main(String[] args) {

System.out.println("Hello, world!");

}

}

• What does this code output (print to the user) when you run (execute) it?

5

Page 6: CDIT Java01 00_Introduction to Java

Compiling a program

• Before you run a program, you must compile it.

• compiler: Translates a computer program written in one language (i.e., Java) to another language (i.e., byte code)

6

Compile (javac) Execute (java)

outputsource code(Hello.java)

byte code(Hello.class)

Page 7: CDIT Java01 00_Introduction to Java

The Java Virtual Machine (JVM, or VM)

• The Java Virtual Machine executes byte code– Use the “java” command to execute it

– It only understands byte code (“.class” files)

• The VM makes Java a bit different from older programming languages (C, C++)– It’s an extra step; compilers for other languages

directly produce machine code

– It’s slower

– But it allows the same byte code to run on any machine with a VM

Page 8: CDIT Java01 00_Introduction to Java

Program execution

• The output is printed to the console.

• Some editors pop up the console as another window.

8

Page 9: CDIT Java01 00_Introduction to Java

Another Java program

public class Hello2 {

public static void main(String[] args) {

System.out.println("Hello, world!");

System.out.println();

System.out.println("This program produces");

System.out.println("four lines of output");

}

}

9

Page 10: CDIT Java01 00_Introduction to Java

Syntax

• syntax: The set of legal structures and commands that can be used.

• Examples:

– Every basic statement ends with a semi-colon.

– The contents of a class occur between curly braces.

10

Page 11: CDIT Java01 00_Introduction to Java

Syntax Errors

• syntax error: A problem in the structure of a program.

1 public class Hello {

2 pooblic static void main(String[] args) {

3 System.owt.println("Hello, world!")

4 }

5 }

11

2 errors found:

File: Hello.java [line: 2]

Error: Hello.java:2: <identifier> expected

File: Hello.java [line: 3]

Error: Hello.java:3: ';' expected

compiler output:

Page 12: CDIT Java01 00_Introduction to Java

More on syntax errors

• Java is case-sensitive– Hello and hello are not the same

1 Public class Hello {

2 public static void main(String[] args) {

3 System.out.println("Hello, world!");

4 }

5 }

12

1 error found:

File: Hello.java [line: 1]

Error: Hello.java:1: class, interface, or enum

expected

compiler output:

Page 13: CDIT Java01 00_Introduction to Java

System.out.println

• System.out.println: A statement to print a line of output to the console.

– pronounced “print-linn”

• Two ways to use System.out.println:

System.out.println("<message>");

– Prints the given message as a line of text to the console.

System.out.println();

– Prints a blank line to the console.

13

Page 14: CDIT Java01 00_Introduction to Java

Primitive data types,

expressions, and variables

14

Page 15: CDIT Java01 00_Introduction to Java

Primitive types

• Java has eight primitive types. Here are two examples:

Name Description Examples

int integers 42, -3, 0, 926394

double real numbers 3.4, -2.53, 91.4e3

• Numbers with a decimal point are treated as real numbers.

• Question: Isn’t every integer a real number? Why bother?

15

Page 16: CDIT Java01 00_Introduction to Java

Other Primitive Data Types

Discrete Types

byte

short

int

long

16

Continuous Types

float

double

Non-numeric Types

boolean

char

Page 17: CDIT Java01 00_Introduction to Java

Data Type Representations

Type Representation Bits Bytes #Values

boolean true or false 1 N/A 2

char ‘a’ or ‘7’ or ‘\n’ 16 2 216 = 65,536

byte …,-2,-1,0,1,2,… 8 1 28 = 256

short …,-2,-1,0,1,2,… 16 2 216 = 65,536

int …,-2,-1,0,1,2,… 4 > 4.29 million

long …,-2,-1,0,1,2,… 8 > 18 quintillion

float 0.0, 10.5, -100.7 32

double 0.0, 10.5, -100.7 64

Page 18: CDIT Java01 00_Introduction to Java

Precision in real numbers

• The computer internally represents real numbers in an imprecise way.

• Example:System.out.println(0.1 + 0.2);

– The output is 0.30000000000000004!

18

Page 19: CDIT Java01 00_Introduction to Java

Concatenation: Operating on strings

• string concatenation: Using the + operator between a string and another value to make a longer string.

• Examples:"hello" + 42 is "hello42"1 + "abc" + 2 is "1abc2""abc" + 1 + 2 is "abc12"1 + 2 + "abc“ is "3abc""abc" + 9 * 3 is "abc27" (what happened here?)"1" + 1 is "11"4 - 1 + "abc“ is "3abc"

"abc" + 4 - 1causes a compiler error. Why?

19

Page 20: CDIT Java01 00_Introduction to Java

Overflow example

int n = 2000000000;

System.out.println(n * n);

// output: -1651507200

• the result of n*n is 4,000,000,000,000,000,000 which needs 64-bits:

---------- high-order bytes -------

00110111 10000010 11011010 11001110

---------- low order bytes --------

10011101 10010000 00000000 00000000

• In the case of overflow, Java discards the high-order bytes, retaining only the low-order ones

• In this case, the low order bytes represent 1651507200, and since the right most bit is a 1 the sign value is negative.

Page 21: CDIT Java01 00_Introduction to Java

Declaring variables

• To create a variable, it must be declared.

• Variable declaration syntax:<type> <name>;

• Convention: Variable identifiers follow the same rules as method names.

• Examples:int x;

double myGPA;

int varName;

21

Page 22: CDIT Java01 00_Introduction to Java

Identifiers: Keywords

• keyword: An identifier that you cannot use, because it already has a reserved meaning in the Java language.

• Complete list of Java keywords:abstract default if private this

boolean do implements protected throw

break double import public throws

byte else instanceof return transient

case extends int short try

catch final interface static void

char finally long strictfp volatile

class float native super while

const for new switch

continue goto package synchronized

• NB: Because Java is case-sensitive, you could technically use Class or cLaSs

as identifiers, but this is very confusing and thus strongly discouraged.

22

Page 23: CDIT Java01 00_Introduction to Java

Increment and decrement

• Incrementing and decrementing 1 is used often enough that they have a special shortcut operator!

Shorthand Equivalent longer version<variable>++; <variable> = <variable> + 1;

<variable>--; <variable> = <variable> - 1;

• Examples:int x = 2;

x++; // x = x + 1;

// x now stores 3

double gpa = 2.5;

gpa++; // gpa = gpa + 1;

// gpa now stores 3.5

23

Page 24: CDIT Java01 00_Introduction to Java

24

if/else statements

Page 25: CDIT Java01 00_Introduction to Java

The if statement

• if statement: A control structure that executes a block of statements only if a certain condition is true.

• General syntax:if (<test>) {

<statement(s)> ;

}

• Example (with grade inflation):if (gpa >= 2.0) {

System.out.println("You get an A!");

}

25

Page 26: CDIT Java01 00_Introduction to Java

if statement flow chart

26

Page 27: CDIT Java01 00_Introduction to Java

The if/else statement

• if/else statement: A control structure that executes one block of statements if a certain condition is true, and a second block of statements if it is false. We refer to each block as a branch.

• General syntax:if (<test>) {

<statement(s)> ;} else {

<statement(s)> ;}

• Example:if (gpa >= 3.0) {

System.out.println("Welcome to Temple!");

} else {

System.out.println("Try applying to Penn.");

}

27

Page 28: CDIT Java01 00_Introduction to Java

if/else statement flow chart

28

Page 29: CDIT Java01 00_Introduction to Java

Chained if/else statements

• Chained if/else statement: A chain of if/else that can select between many different outcomes based on several tests.

• General syntax:if (<test>) {

<statement(s)> ;} else if (<test>) {

<statement(s)> ;} else {

<statement(s)> ;}

• Example:if (number > 0) {

System.out.println("Positive");

} else if (number < 0) {

System.out.println("Negative");

} else {

System.out.println("Zero");

}

29

Page 30: CDIT Java01 00_Introduction to Java

Chained if/else flow chart

30

if (<test>) {

<statement(s)>;

} else if (<test>) {

<statement(s)>;

} else {

<statement(s)>;

}

Page 31: CDIT Java01 00_Introduction to Java

Chained if/else if flow chart

31

if (<test>) {

<statement(s)>;

} else if (<test>) {

<statement(s)>;

} else if (<test>) {

<statement(s)>;

}

Page 32: CDIT Java01 00_Introduction to Java

Boolean Arithmetic

32

Page 33: CDIT Java01 00_Introduction to Java

The boolean Type

33

The boolean type has two possible values:true and false

boolean variables are declared and initialized just like other primitive data types:

boolean iAmSoSmrt = false; //just like

int i = 2;

boolean minor = (age < 21); //just like

int x = y*2;

Page 34: CDIT Java01 00_Introduction to Java

Relational expressions

• Relational expressions have

– numeric arguments and

– boolean values.

• They use one of the following six relational operators:

34

true5.0 >= 5.0greater than or equal to>=

false126 <= 100less than or equal to<=

true10 > 5greater than>

false10 < 5less than<

true3.2 != 2.5does not equal!=

true1 + 1 == 2equals==

ValueExampleMeaningOperator

Page 35: CDIT Java01 00_Introduction to Java

Evaluating Relational expressions

• Relational operators have lower precedence than math operators.

5 * 7 >= 3 + 5 * (7 - 1)

5 * 7 >= 3 + 5 * 6

35 >= 3 + 30

35 >= 33

true

• Relational operators cannot be chained (unlike math operators)

2 <= x <= 10

true <= 10

error!

35

Page 36: CDIT Java01 00_Introduction to Java

Logical operators

• Logical operators have

– boolean arguments and

– boolean values

36

!(7 > 0)

(2 == 3) || (-1 < 5)

(9 != 6) && (2 < 3)

Example

not

or

and

Description

!

||

true&&

ResultOperator

Page 37: CDIT Java01 00_Introduction to Java

Boolean expressions

• What is the result of each of the following expressions?int x = 42;

int y = 17;

int z = 25;

– y < x && y <= z

– x % 2 == y % 2 || x % 2 == z % 2

– x <= y + z && x >= y + z

– !(x < y && x < z)

– (x + y) % 2 == 0 || !((z - y) % 2 == 0)

Answers: true, false, true, true, false

37

Page 38: CDIT Java01 00_Introduction to Java

Class Constants

A class constant is a variable

– whose scope is the entire class, and

– whose value can never change after it has been initialized.

To give it the right scope, simply declare it right inside the class:

public class MyClass {

public static final int myConstant = 4;

}

The final keyword means its value can’t be changed.

Page 39: CDIT Java01 00_Introduction to Java

The for loop

39

Page 40: CDIT Java01 00_Introduction to Java

Looping via the for loop

• for loop: A block of Java code that executes a group of statements repeatedly until a given test fails.

• General syntax:for (<initialization>; <test>; <update>) {

<statement>;

<statement>;

...

<statement>;

}

• Example:for (int i = 1; i <= 30; i++) {

System.out.println("I will not throw...");

}

40

Page 41: CDIT Java01 00_Introduction to Java

Control Structure

• The for loop is a control structure—a syntactic

structure that controls the execution of other statements.

• Example:

– “Shampoo hair. Rinse. Repeat.”

41

Page 42: CDIT Java01 00_Introduction to Java

for loop over range of ints

• We'll write for loops over integers in a given range.

– The <initialization> declares a loop counter variable that is used in the test, update, and body of the loop.

for (int <name> = 1; <name> <= <value>; <name>++) {

• Example:for (int i = 1; i <= 4; i++) {

System.out.println(i + " squared is " + (i * i));

}

Output:1 squared is 1

2 squared is 4

3 squared is 9

4 squared is 16

42

Page 43: CDIT Java01 00_Introduction to Java

for loop flow diagram

43

for (<init>; <test>; <update>) {

<statement>;

<statement>;

...

<statement>;

}

Page 44: CDIT Java01 00_Introduction to Java

Loop walkthrough

• Code:for (int i = 1; i <= 3; i++) {

System.out.println(i + " squared is " + (i * i));

}

Output:1 squared is 1

2 squared is 4

3 squared is 9

44

i:

Page 45: CDIT Java01 00_Introduction to Java

Loop example

• Code:System.out.println("+----+");

for (int i = 1; i <= 3; i++) {

System.out.println("\\ /");

System.out.println("/ \\");

}

System.out.println("+----+");

Output:+----+

\ /

/ \

\ /

/ \

\ /

/ \

+----+

45

Page 46: CDIT Java01 00_Introduction to Java

Varying the for loop

• The initial and final values for the loop counter variable can be arbitrary expressions:

• Example:for (int i = -3; i <= 2; i++) {

System.out.println(i);

}

Output:-3

-2-10

12

• Example:for (int i = 1 + 3 * 4; i <= 5248 % 100; i++) {

System.out.println(i + " squared is " + (i * i));

}

46

Page 47: CDIT Java01 00_Introduction to Java

Varying the for loop

• The update can be a -- (or any other operator).– Caution: This requires changing the test from <= to >= .

System.out.println("T-minus");

for (int i = 3; i >= 1; i--) {

System.out.println(i);

}

System.out.println("Blastoff!");

Output:T-minus

3

2

1

Blastoff!

47

Page 48: CDIT Java01 00_Introduction to Java

Errors in coding

• ERROR: Loops that never execute.

for (int i = 10; i < 5; i++) {

System.out.println("How many times do I print?");

}

• ERROR: Loop tests that never fail.

– A loop that never terminates is called an infinite loop.

for (int i = 10; i >= 1; i++) {

System.out.println("Runaway Java program!!!");

}

48

Page 49: CDIT Java01 00_Introduction to Java

Nested for loops

• nested loop: Loops placed inside one another.– Caution: Make sure the inner loop's counter variable has a different name!

for (int i = 1; i <= 3; i++) {System.out.println("i = " + i);for (int j = 1; j <= 2; j++) {

System.out.println(" j = " + j);}

}

Output:i = 1j = 1j = 2

i = 2j = 1j = 2

i = 3j = 1j = 2

49

Page 50: CDIT Java01 00_Introduction to Java

Nested loops example

• Code:for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= 10; j++) {

System.out.print((i * j) + " ");

}

System.out.println(); // to end the line

}

Output:1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

50

Page 51: CDIT Java01 00_Introduction to Java

Nested loops example

• Code:for (int i = 1; i <= 6; i++) {

for (int j = 1; j <= 10; j++) {

System.out.print("*");

}

System.out.println();

}

Output:**********

**********

**********

**********

**********

**********

51

Page 52: CDIT Java01 00_Introduction to Java

Nested loops example

• Code:for (int i = 1; i <= 6; i++) {

for (int j = 1; j <= i; j++) {

System.out.print("*");

}

System.out.println();

}

Output:*

**

***

****

*****

******

52

Page 53: CDIT Java01 00_Introduction to Java

Nested loops example

• Code:for (int i = 1; i <= 6; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(i);

}

System.out.println();

}

Output:1

22

333

4444

55555

666666

53

Page 54: CDIT Java01 00_Introduction to Java

Nested loops example

• Code:for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= (5 - i); j++) {

System.out.print(" ");

}

for (int k = 1; k <= i; k++) {

System.out.print(i);

}

System.out.println();

}

Output:1

22

333

4444

55555

54

Page 55: CDIT Java01 00_Introduction to Java

Exercise: Nested loops

• What nested for loops produce the following output?

....1

...2

..3

.4

5

• Key idea:– outer "vertical" loop for each of the lines– inner "horizontal" loop(s) for the patterns within each line

55

inner loop (repeated characters on each line)

outer loop (loops 5 times because there are 5 lines)

Page 56: CDIT Java01 00_Introduction to Java

Nested loops

• First, write the outer loop from 1 to the number of lines desired.

for (int line = 1; line <= 5; line++) {

...

}

• Notice that each line has the following pattern:– some number of dots (0 dots on the last line)

– a number

....1

...2

..3

.4

5

56

Page 57: CDIT Java01 00_Introduction to Java

Nested loops

• Make a table:

....1

...2

..3

.4

5

• Answer:for (int line = 1; line <= 5; line++) {

for (int j = 1; j <= (line * -1 + 5); j++) {

System.out.print(".");

}

System.out.println(line);

}

57

0

1

2

3

4

line * -1 + 5

414

0

2

3

4

# of dots

5

3

2

1

value displayed

5

3

2

1

line

Page 58: CDIT Java01 00_Introduction to Java

Errors in coding

• ERROR: Using the wrong loop counter variable.

– What is the output of the following piece of code?for (int i = 1; i <= 10; i++) {

for (int j = 1; i <= 5; j++) {

System.out.print(j);

}

System.out.println();

}

– What is the output of the following piece of code?for (int i = 1; i <= 10; i++) {

for (int j = 1; j <= 5; i++) {

System.out.print(j);

}

System.out.println();

}

58

Page 59: CDIT Java01 00_Introduction to Java

while loops

59

Page 60: CDIT Java01 00_Introduction to Java

Definite loops

• definite loop: A loop that executes a known number of times.– The for loops we have seen so far are definite loops.

• We often use language like

– "Repeat these statements N times."

– "For each of these 10 things, …"

• Examples:

– Print "hello" 10 times.

– Find all the prime numbers up to an integer n.

60

Page 61: CDIT Java01 00_Introduction to Java

Indefinite loops

• indefinite loop: A loop where it is not obvious in advance how many times it will execute.

• We often use language like

– "Keep looping as long as or while this condition is still true."

– "Don't stop repeating until the following happens."

• Examples:

– Print random numbers until a prime number is printed.

– Continue looping while the user has not typed "n" to quit.

61

Page 62: CDIT Java01 00_Introduction to Java

while loop

• while loop: A control structure that repeatedly performs a test and executes a group of statements if the test evaluates to true.

• while loop, general syntax:while (<test>) {

<statement(s)>;}

• Example:int number = 1;

while (number <= 200) {

System.out.print(number + " ");

number *= 2;

}

Output:1 2 4 8 16 32 64 128

62

Page 63: CDIT Java01 00_Introduction to Java

while loop flow chart

63

Page 64: CDIT Java01 00_Introduction to Java

Example

• Finds and prints a number's first factor other than 1:

Scanner console = new Scanner(System.in);

System.out.print("Type a number: ");

int number = console.nextInt();

int factor = 2;

while (number % factor != 0) {

factor++;

}

System.out.println("First factor: " + factor);

Sample run:Type a number: 91

First factor: 7

64

Page 65: CDIT Java01 00_Introduction to Java

for vs. while

• Any for loop of the following form:

for (<initialization>; <test>; <update>) {<statement(s)>;

}

is equivalent to a while loop of the following form:

<initialization>;while (<test>) {

<statement(s)>;<update>;

}

65

Page 66: CDIT Java01 00_Introduction to Java

for vs. while: Example

• What while loop is equivalent to the following for loop?

for (int i = 1; i <= 10; i++) {

System.out.println(i + " squared = " + (i * i));

}

Solution:

int i = 1;

while (i <= 10) {

System.out.println(i + " squared = " + (i * i));

i++;

}

66

Page 67: CDIT Java01 00_Introduction to Java

Exercise: digitSum

• Write a class named DigitSum that reads an integer from

the user and prints the sum of the digits of that number. You may assume that the number is non-negative.

Example:

Enter a nonnegative number: 29107

prints 2+9+1+0+7 or 19

• Hint: Use the % operator to extract the last digit of a

number. If we do this repeatedly, when should we stop?

67

Page 68: CDIT Java01 00_Introduction to Java

Solution: digitSum

import java.util.Scanner;

public class DigitSum {

public static void main(String [] args) {

Scanner keyboard = new Scanner(System.in);

int n = keyboard.nextInt();

int sum = 0;

while (n > 0) {

sum += n % 10; // add last digit to sum

n = n / 10; // remove last digit

}

System.out.println(“sum = “ + sum);

}

}

68

Page 69: CDIT Java01 00_Introduction to Java

Random numbers

69

Page 70: CDIT Java01 00_Introduction to Java

The Random class

• Objects of the Random class generate pseudo-random

numbers.– Class Random is found in the java.util package.

import java.util.*;

• The methods of a Random object

70

returns a random real number in the range [0.0, 1.0)nextDouble()

returns a random integer in the range [0, max)

in other words, from 0 to one less than max

nextInt(max)

returns a random integernextInt()

DescriptionMethod name

Page 71: CDIT Java01 00_Introduction to Java

Generating random numbers

Random rand = new Random();

int randomNum = rand.nextInt(10);

// randomNum has a random value between 0 and 9

• What if we wanted a number from 1 to 10?int randomNum = rand.nextInt(10) + 1;

• What if we wanted a number from min to max (i.e. an arbitrary range)?int randomNum = rand.nextInt(<size of the range>) +

<min>

where <size of the range> equals (<max> - <min> + 1)

71

Page 72: CDIT Java01 00_Introduction to Java

Random questions

• Given the following declaration, how would you get:Random rand = new Random();

– A random number between 0 and 100 inclusive?

– A random number between 1 and 100 inclusive?

– A random number between 4 and 17 inclusive?

72

Page 73: CDIT Java01 00_Introduction to Java

Random solutions

• Given the following declaration, how would you get:Random rand = new Random();

– A random number between 0 and 100 inclusive?int random1 = rand.nextInt(101);

– A random number between 1 and 100 inclusive?int random1 = rand.nextInt(100) + 1;

– A random number between 4 and 17 inclusive?int random1 = rand.nextInt(14) + 4;

73

Page 74: CDIT Java01 00_Introduction to Java

Exercise: Die-rolling

• Write a program that simulates the rolling of two six-sided dice until their combined result comes up as 7.

Sample run:Roll: 2 + 4 = 6

Roll: 3 + 5 = 8

Roll: 5 + 6 = 11

Roll: 1 + 1 = 2

Roll: 4 + 3 = 7

You won after 5 tries!

74

Page 75: CDIT Java01 00_Introduction to Java

Solution: Die-rolling

import java.util.*;

public class Roll {

public static void main(String[] args) {

Random rand = new Random();

int sum = 0;

int tries = 0;

while (sum != 7) {

int roll1 = rand.nextInt(6) + 1;

int roll2 = rand.nextInt(6) + 1;

sum = roll1 + roll2;

System.out.println("Roll: " + roll1 + " + " + roll2 + " = " + sum);

tries++;

}

System.out.println("You won after " + tries + " tries!");

}

}

75

Page 76: CDIT Java01 00_Introduction to Java

Scanner objects

76

Page 77: CDIT Java01 00_Introduction to Java

Interactive programs

• We have written programs that print console output.

• It is also possible to read input from the console.

– The user types the input into the console.

– The program uses the input to do something.

– Such a program is called an interactive program.

77

Page 78: CDIT Java01 00_Introduction to Java

Scanner

• Constructing a Scanner object to read the console:

Scanner <name> = new Scanner(System.in);

• Example:

Scanner console = new Scanner(System.in);

78

Page 79: CDIT Java01 00_Introduction to Java

Scanner methods

• Some methods of Scanner:

• Each of these methods pauses your program until the user types input and presses Enter.– Then the value typed is returned to your program.

79

reads and returns user input as a doublenextDouble()

reads and returns user input as an intnextInt()

reads and returns user input as a Stringnext()

DescriptionMethod

Page 80: CDIT Java01 00_Introduction to Java

Using a Scanner object

• Example:

System.out.print("How old are you? "); // prompt

int age = console.nextInt();

System.out.println("You'll be 40 in " + (40 -age)

+ " years.");

• prompt: A message printed to the user, telling them what input to type.

80

Page 81: CDIT Java01 00_Introduction to Java

Input tokens

• token: A unit of user input, as read by the Scanner.– Tokens are separated by whitespace (spaces, tabs, new lines).– How many tokens appear on the following line of input?

23 John Smith 42.0 "Hello world"

• When the token doesn't match the type the Scanner tries to read, the program crashes.– Example:

System.out.print("What is your age? ");

int age = console.nextInt();

Sample Run:What is your age? Timmy

InputMismatchException:

at java.util.Scanner.throwFor(Unknown Source)

at java.util.Scanner.next(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

...

81

Page 82: CDIT Java01 00_Introduction to Java

Importing classes

• Java class libraries: A large set of Java classes available for you to use.– Classes are grouped into packages.

– To use the classes from a package, you must include an import declaration at the top of your program.

– Scanner is in a package named java.util

• Import declaration, general syntax:import <package name>.*;

• To use Scanner, put this at the start of your program:import java.util.*;

82

Page 83: CDIT Java01 00_Introduction to Java

A complete program

import java.util.*; // so that I can use Scanner

public class ReadSomeInput {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

System.out.print("What is your first name? ");

String name = console.next();

System.out.print("And how old are you? ");

int age = console.nextInt();

System.out.println(name + " is " + age + ". That's quite old!");

}

}

Sample Run:What is your first name? Marty

How old are you? 12

Marty is 12. That's quite old!

83

Page 84: CDIT Java01 00_Introduction to Java

Another complete program

import java.util.*; // so that I can use Scanner

public class Average {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

System.out.print("Please type three numbers: ");

int num1 = console.nextInt();

int num2 = console.nextInt();

int num3 = console.nextInt();

double average = (num1 + num2 + num3) / 3.0;

System.out.println("The average is " + average);

}

}

Sample Run:Please type three numbers: 8 6 13

The average is 9.0

• Notice that the Scanner can read multiple values from one line.

84