01 java language

Upload: minotoji-mi

Post on 02-Jun-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 01 Java Language

    1/102

    PHN 1:

    NGN NG JAVA

    BI 1: LM QUEN VI NGN NG JAVA

  • 8/11/2019 01 Java Language

    2/102

    Java History

    James Gosling and Sun Microsystems

    Oak

    Java, May 20, 1995, Sun World

    HotJava The first Java-enabled Web browser

    JDK Evolutions

    J2SE, J2ME, and J2EE

    215/09/2014

  • 8/11/2019 01 Java Language

    3/102

    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.

    315/09/2014

  • 8/11/2019 01 Java Language

    4/102

    Java IDE Tools

    Text Pad

    Net Bean

    EClipse

    415/09/2014

  • 8/11/2019 01 Java Language

    5/102

    5

    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 yourun(execute) it?

  • 8/11/2019 01 Java Language

    6/102

    6

    Compiling a program

    Before you run a program, you must compileit.

    compiler:Translates a computer program

    written in one language (i.e., Java) to another

    language (i.e., byte code)

    Compile (javac) Execute (java)

    outputsource code

    (Hello.java)

    byte code

    (Hello.class)

  • 8/11/2019 01 Java Language

    7/102

    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++)

    Its an extra step; compilers for other languagesdirectly produce machine code

    Its slower

    But it allows the same byte code to run on any

    machine with a VM

  • 8/11/2019 01 Java Language

    8/102

    8

    Program execution

    The outputis printed to the console.

    Some editors pop up the console as another window.

  • 8/11/2019 01 Java Language

    9/102

    9

    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");

    }

    }

  • 8/11/2019 01 Java Language

    10/102

    10

    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.

  • 8/11/2019 01 Java Language

    11/102

    11

    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 }

    2 errors found:File:Hello.java [line: 2]

    Error:Hello.java:2: expected

    File:Hello.java [line: 3]

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

    compiler output:

  • 8/11/2019 01 Java Language

    12/102

    12

    More on syntax errors

    Java is case-sensitive

    Helloand helloare not the same

    1 Public class Hello {

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

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

    4 }

    5 }

    1 error found:

    File:Hello.java [line: 1]

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

    expected

    compiler output:

  • 8/11/2019 01 Java Language

    13/102

    13

    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("");

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

    System.out.println();

    Prints a blank line to the console.

  • 8/11/2019 01 Java Language

    14/102

    14

    Strings

    string:A sequence of text characters.

    Start and end with quotation mark characters

    Examples:

    "hello"

    "This is a string"

    "This, too, is a string. It can be very long!"

  • 8/11/2019 01 Java Language

    15/102

    15

    Details about strings

    A string may not span across multiple lines."This is not

    a legal string."

    A string may not contain a character.

    The character is okay.

    "This is not a "legal" string either."

    "This is 'okay' though."

    This begs the question

  • 8/11/2019 01 Java Language

    16/102

    16

    Escape sequences

    A string can represent certain special characters by preceding themwith a backslash \(this is called an escape sequence). \t tab character

    \n newline character

    \" quotation mark character

    Example:System.out.println("Hello!\nHow are \"you\"?");

    Output:

    Hello!

    How are "you"?

    This begs another question

  • 8/11/2019 01 Java Language

    17/102

    17

    Comments

    comment: A note written in the source code to make the code easier tounderstand.

    Comments are not executed when your program runs.

    Most Java editors show your comments with a special color.

    Comment, general syntax:

    /* */

    or,

    //

    Examples:

    /* A comment goes here. *//* It can even span

    multiple lines. */

    // This is a one-line comment.

  • 8/11/2019 01 Java Language

    18/102

    18

    Comments: Where do you go?

    at the top of each file (also called a "comment header"), naming

    the author and explaining what the program does

    at the start of every method, describing its behavior

    inside methods, to explain complex pieces of code

  • 8/11/2019 01 Java Language

    19/102

    19

    Comments: Why?

    Comments provide important documentation.

    Later programs will span hundreds or thousands of lines, split into

    many classes and methods.

    Comments provide a simple description of what each class, method,

    etc. is doing.

    When multiple programmers work together, comments help one

    programmer understand the other's code.

  • 8/11/2019 01 Java Language

    20/102

    20

    That thing called style

    What is style?

    Indentation

    Capitalization

    Formatting / spacing

    Structured code

    No redundancy

    Why is it important?

  • 8/11/2019 01 Java Language

    21/102

    21

    Primitive data types,

    expressions, and

    variables

  • 8/11/2019 01 Java Language

    22/102

    22

    How the computer sees the world

    Internally, the computer stores everything in terms of 1s

    and 0s

    Example:

    h 0110100

    "hi" 01101000110101

    104 0110100

    How can the computer tell the difference between an h

    and 104?

  • 8/11/2019 01 Java Language

    23/102

    23

    Data types

    data type: A category of data values.

    Example: integer, real number, string

    Data types are divided into two classes:

    primitive types: Java's built-in simpledata types for

    numbers, text characters, and logic.

    object types: Coming soon!

  • 8/11/2019 01 Java Language

    24/102

    24

    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: Isnt every integer a real number? Why bother?

  • 8/11/2019 01 Java Language

    25/102

    25

    Other Primitive Data Types

    Discrete Typesbyte

    short

    intlong

    Continuous Typesfloat

    double

    Non-numeric Types

    booleanchar

  • 8/11/2019 01 Java Language

    26/102

    Data Type Representations

    Type Representation Bits Bytes #Valuesboolean trueor 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

  • 8/11/2019 01 Java Language

    27/102

    27

    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!

  • 8/11/2019 01 Java Language

    28/102

    28

    Concatenation: Operating on strings

    string concatenation: Using the +operator between a stringand 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?

  • 8/11/2019 01 Java Language

    29/102

    Question

    ints are stored in 4 bytes (32 bits)

    In 32 bits, we can store at most 232different

    numbers

    What happens if we take the largest of these,

    and add 1 to it?

    ERROR!

    This is known as overflow: trying to store somethingthat does not fit into the bits reserved for a data type.

    Overflow errors are NOTautomatically detected!

    Its the programmers responsibility to prevent these.

    The actual result in this case is a negative number.

  • 8/11/2019 01 Java Language

    30/102

    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.

  • 8/11/2019 01 Java Language

    31/102

    31

    Declaring variables

    To create a variable, it must be declared.

    Variable declaration syntax:;

    Convention: Variable identifiers follow the samerules as method names.

    Examples:int x;

    double myGPA;

    int varName;

  • 8/11/2019 01 Java Language

    32/102

    32

    Declaring a variable sets aside a piece of memory inwhich you can store a value.

    int x;int y;

    Inside the computer:

    x: ? y: ?

    (The memory still has no value yet.)

    Declaring variables

  • 8/11/2019 01 Java Language

    33/102

    33

    Identifiers: Say my name!

    identifier: A name given to an entity in a program such as a class or

    method.

    Identifiers allow us to refer to the entities.

    Examples (in bold): public class Hello

    public static voidmain

    doublesalary

    Conventions for naming in Java (which we will follow):

    classes: capitalize each word (ClassName)

    everything else: capitalize each word after the first(myLastName)

  • 8/11/2019 01 Java Language

    34/102

    34

    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 throwsbyte 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 Classor cLaSs

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

  • 8/11/2019 01 Java Language

    35/102

    35

    Errors in coding

    ERROR:Declaring two variables with the same

    name

    Example:int x;

    int x; // ERROR: x already exists

    ERROR:Reading a variables value before it has

    been assigned

    Example:int x;

    System.out.println(x); // ERROR: x has no value

  • 8/11/2019 01 Java Language

    36/102

    36

    Increment and decrement

    Incrementingand decrementing1is used often enough that they have aspecial shortcut operator!

    Shor thand Equivalent longer vers ion

    ++; = + 1;

    --; = - 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

  • 8/11/2019 01 Java Language

    37/102

    37

    if/elsestatements

  • 8/11/2019 01 Java Language

    38/102

    38

    The ifstatement

    ifstatement: A control structurethat executes a block ofstatements only if a certain condition is true.

    General syntax:

    if () { ;

    }

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

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

    }

  • 8/11/2019 01 Java Language

    39/102

    39

    ifstatement flow chart

  • 8/11/2019 01 Java Language

    40/102

    40

    The if/elsestatement

    if/elsestatement: A control structure that executes one block ofstatements if a certain condition is true, and a second block ofstatements if it is false. We refer to each block as a branch.

    General syntax:

    if () { ;

    } else {

    ;

    }

    Example:if (gpa >= 3.0) {

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

    } else {

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

    }

  • 8/11/2019 01 Java Language

    41/102

    41

    if/elsestatement flow chart

  • 8/11/2019 01 Java Language

    42/102

    42

    Chained if/elsestatements

    Chained if/elsestatement: A chain of if/elsethat can selectbetween many different outcomes based on several tests.

    General syntax:if () {

    ;

    } else if () {

    ;} else {

    ;

    }

    Example:if (number > 0) {

    System.out.println("Positive");

    } else if (number < 0) {System.out.println("Negative");

    } else {System.out.println("Zero");

    }

  • 8/11/2019 01 Java Language

    43/102

    43

    Chained if/elseflow chart

    if () {

    ;

    } else if () {

    ;

    } else {

    ;

    }

  • 8/11/2019 01 Java Language

    44/102

    44

    Chained if/elseifflow chart

    if () {

    ;

    } else if () {

    ;

    } else if () {

    ;

    }

  • 8/11/2019 01 Java Language

    45/102

    45

    Boolean Arithmetic

  • 8/11/2019 01 Java Language

    46/102

    46

    ThebooleanType

    The booleantype has two possible values:true and false

    booleanvariables are declared and initializedjust like other primitive data types:

    boolean iAmSoSmrt = false; //just like int i = 2;

    boolean minor = (age < 21); //just like int x = y*2;

  • 8/11/2019 01 Java Language

    47/102

    47

    Relational expressions

    Relational expressionshave

    numeric arguments and

    boolean values.

    They use one of the following six relational operators:

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

    false126

    false10 < 5less than= 3 + 5 * (7 - 1)

    5 * 7>= 3 + 5 * 6

    35 >= 3 + 30

    35 >= 33

    true

    Relational operators cannot be chained (unlike math

    operators)2

  • 8/11/2019 01 Java Language

    49/102

    49

    Logical operators

    Logical operatorshave

    boolean arguments and

    boolean values

    !(7 > 0)

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

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

    Example

    not

    or

    and

    Description

    !

    ||

    true&&

    ResultOperator

  • 8/11/2019 01 Java Language

    50/102

    50

    What is the result of each of the following expressions?

    int x = 42;

    int y = 17;

    int z = 25;

    y < x && y

  • 8/11/2019 01 Java Language

    51/102

    Class Constants

    A class constant is a variable

    whose scopeis the entire class, and

    whose valuecan 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 finalint myConstant = 4;

    }

  • 8/11/2019 01 Java Language

    52/102

    52

    The forloop

  • 8/11/2019 01 Java Language

    53/102

    53

    Looping via the forloop

    forloop: A block of Java code that executes a group of statementsrepeatedly until a given test fails.

    General syntax:for (; ; ) {

    ;;

    ...

    ;

    }

    Example:for (int i = 1; i

  • 8/11/2019 01 Java Language

    54/102

    54

    Control Structure

    The forloop is a con tro l st ructurea syntactic

    structure that controlsthe execution of other

    statements.

    Example:

    Shampoo hair. Rinse. Repeat.

  • 8/11/2019 01 Java Language

    55/102

    55

    forloop over range of ints

    We'll write forloops over integers in a given range. The declares a loop counter variable that is used in the test,

    update, and body of the loop.

    for (int = 1;

  • 8/11/2019 01 Java Language

    56/102

    56

    forloop flow diagramfor (; ; ) {

    ;

    ;...

    ;

    }

  • 8/11/2019 01 Java Language

    57/102

    57

    Loop walkthrough

    Code:for (int i = 1; i

  • 8/11/2019 01 Java Language

    58/102

    58

    Loop example

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

    for (int i = 1; i

  • 8/11/2019 01 Java Language

    59/102

    59

    Varying the forloop

    The initial and final values for the loop counter variable can be arbitraryexpressions:

    Example:for (int i = -3; i

  • 8/11/2019 01 Java Language

    60/102

    60

    Varying the forloop

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

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

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

    System.out.println(i);

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

    Output:T-minus

    3

    21

    Blastoff!

  • 8/11/2019 01 Java Language

    61/102

    61

    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!!!");

    }

  • 8/11/2019 01 Java Language

    62/102

    62

    Nested forloops

    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

  • 8/11/2019 01 Java Language

    63/102

    63

    Nested loops example

    Code:for (int i = 1; i

  • 8/11/2019 01 Java Language

    64/102

    64

    Nested loops example

    Code:for (int i = 1; i

  • 8/11/2019 01 Java Language

    65/102

    65

    Nested loops example

    Code:for (int i = 1; i

  • 8/11/2019 01 Java Language

    66/102

    66

    Nested loops example

    Code:for (int i = 1; i

  • 8/11/2019 01 Java Language

    67/102

    67

    Nested loops example

    Code:for (int i = 1; i

  • 8/11/2019 01 Java Language

    68/102

    68

    Exercise: Nested loops

    What nested forloops 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

    inner loop (repeated characters on each line)

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

  • 8/11/2019 01 Java Language

    69/102

    69

    Nested loops

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

    for (int line = 1; line

  • 8/11/2019 01 Java Language

    70/102

    70

    Nested loops

    Make a table:

    ....1

    ...2

    ..3

    .4

    5

    Answer:for (int line = 1; line

  • 8/11/2019 01 Java Language

    71/102

    71

    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

  • 8/11/2019 01 Java Language

    72/102

    72

    whileloops

  • 8/11/2019 01 Java Language

    73/102

    73

    Definite loops

    definite loop: A loop that executes a known number oftimes.

    The forloops we have seen so far are definite loops.

    We often use language like "Repeat these statements Ntimes."

    "For each of these 10 things, "

    Examples: Print "hello" 10 times.

    Find all the prime numbers up to an integer n.

  • 8/11/2019 01 Java Language

    74/102

    74

    Indefinite loops

    indefinite loop: A loop where it is not obvious in advancehow many times it will execute.

    We often use language like

    "Keep looping as long asor whilethis condition is still true."

    "Don't stop repeating untilthe following happens."

    Examples:

    Print random numbers until a prime number is printed.

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

  • 8/11/2019 01 Java Language

    75/102

  • 8/11/2019 01 Java Language

    76/102

    76

    whileloop flow chart

  • 8/11/2019 01 Java Language

    77/102

    77

    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

  • 8/11/2019 01 Java Language

    78/102

    78

    forvs.while

    Any forloop of the following form:

    for (; ; ) {

    ;

    }

    is equivalent to a whileloop of the following form:

    ;

    while () {;

    ;

    }

  • 8/11/2019 01 Java Language

    79/102

    79

    forvs.while: Example

    What whileloop is equivalent to the following forloop?for (int i = 1; i

  • 8/11/2019 01 Java Language

    80/102

    80

    Exercise: digitSum

    Write a class named DigitSumthat reads an integer fromthe 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 anumber. If we do this repeatedly, when should we stop?

    S

  • 8/11/2019 01 Java Language

    81/102

    81

    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);

    }

    }

  • 8/11/2019 01 Java Language

    82/102

    82

    Random numbers

    Th l

  • 8/11/2019 01 Java Language

    83/102

    83

    The Randomclass

    Objects of the Randomclass generatepseudo-randomnumbers.

    Class Randomis found in the java.utilpackage.

    import java.util.*;

    The methods of a Randomobject

    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

    G

  • 8/11/2019 01 Java Language

    84/102

    84

    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 minto max(i.e. an

    arbitrary range)?

    int randomNum = rand.nextInt() +

    where equals (- + 1)

    R d i

  • 8/11/2019 01 Java Language

    85/102

    85

    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?

    R d l ti

  • 8/11/2019 01 Java Language

    86/102

    86

    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;

    E i Di lli

  • 8/11/2019 01 Java Language

    87/102

    87

    Exercise: Die-rolling

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

    Sample run:

    Roll: 2 + 4 = 6Roll: 3 + 5 = 8

    Roll: 5 + 6 = 11

    Roll: 1 + 1 = 2

    Roll: 4 + 3 = 7

    You won after 5 tries!

    S l ti Di lli

  • 8/11/2019 01 Java Language

    88/102

    88

    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!");

    }

    }

  • 8/11/2019 01 Java Language

    89/102

    89

    Indefinite loop

    variations

    V i t 1 d / hil

  • 8/11/2019 01 Java Language

    90/102

    90

    Variant 1: do/while

    do/whileloop: A control structure that executes statementsrepeatedly while a condition is true, testing the condition at the endof each repetition.

    do/whileloop, general syntax:do {

    ;

    } while ();

    Example:// roll until we get a number other than 3

    Random rand = new Random();int die;do {

    die = rand.nextInt();} while (die == 3);

    d / hil loop flow chart

  • 8/11/2019 01 Java Language

    91/102

    91

    do/whileloop flow chart

    How does this differ fromthe whileloop?

    The controlledwillalways execute the first

    time, regardless ofwhether the istrue or false.

    V i t 2 "F " l

  • 8/11/2019 01 Java Language

    92/102

    92

    Variant 2: "Forever" loops

    Loops that go on forever

    while (true) {

    ;

    }

    If it goes on forever, how do you stop?

    b king the cycle

  • 8/11/2019 01 Java Language

    93/102

    93

    breaking the cycle

    breakstatement: Immediately exits a loop (for, while,do/while).

    Example:while (true) {

    ;

    if () {

    break;

    }

    ;

    }

    Why is the breakstatement in an ifstatement?

  • 8/11/2019 01 Java Language

    94/102

    94

    Scannerobjects

    Interactive programs

  • 8/11/2019 01 Java Language

    95/102

    95

    Interactive programs

    We have written programs that print console output.

    It is also possible to read inputfrom 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.

    Scanner

  • 8/11/2019 01 Java Language

    96/102

    96

    Scanner

    Constructing a Scannerobject to read the console:Scanner = new Scanner(System.in);

    Example:

    Scanner console = new Scanner(System.in);

    Scanner methods

  • 8/11/2019 01 Java Language

    97/102

    97

    Scannermethods

    Some methods of Scanner:

    Each of these methods pauses your program untilthe user types input and presses Enter.

    Then the value typed is returnedto your program.

    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

    Using a Scanner object

  • 8/11/2019 01 Java Language

    98/102

    98

    Using a Scannerobject

    Example:

    System.out.print("How old are you? "); // promptint 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.

    Input tokens

  • 8/11/2019 01 Java Language

    99/102

    99

    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 Scannertries 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)

    ...

  • 8/11/2019 01 Java Language

    100/102

    A complete program

  • 8/11/2019 01 Java Language

    101/102

    101

    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!

    Another complete program

  • 8/11/2019 01 Java Language

    102/102

    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 S can read multiple values from one line