Basic I/O - CIS 1068 Program Design and Abstraction - PowerPoint PPT Presentation

About This Presentation
Title:

Basic I/O - CIS 1068 Program Design and Abstraction

Description:

Title: PowerPoint Presentation Author: PC User Last modified by: zhen-Air Created Date: 3/11/2001 5:06:34 PM Document presentation format: On-screen Show (4:3) – PowerPoint PPT presentation

Number of Views:305
Avg rating:3.0/5.0
Slides: 84
Provided by: PCU141
Category:

less

Transcript and Presenter's Notes

Title: Basic I/O - CIS 1068 Program Design and Abstraction


1
Basic I/O - CIS 1068 Program Design and
Abstraction
  • Zhen Jiang
  • CIS Dept.
  • Temple University
  • SERC 347, Main Campus
  • Email zhen.jiang_at_temple.edu

2
Table of Contents
  • Your first Java program
  • Simple Output/Input
  • Variable
  • Data types
  • Arithmetic (use of variables)
  • String and its use in I/O statement
  • Summary of programs
  • Summary of concepts
  • Other materials

3
Welcome Your first program
  • http//www.cis.temple.edu/jiang/Welcome.java
  • http//www.cis.temple.edu/jiang/Welcome1.java

4
  • Environment
  • JDK (Java Development Kit)
  • IDE (Integrated Development Environment)
  • Installment guide
  • http//www.cis.temple.edu/jiang/Installment1068.p
    df
  • Test run

5
  • 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
  • Details
  • Names
  • Main
  • and ( )
  • Println and print (p93)

7
  • Textbook
  • Highlighted by content in ppt slides
  • Indexed by page number in ppt slides
  • Discussion
  • Summary
  • Exercises (in ppt slides and class), assignment,
    quiz, test, final

8
(No Transcript)
9
  • Learning target
  • www.cis.temple.edu/jiang/ShowButtonDemo.pdf
  • www.cis.temple.edu/jiang/ButtonDemo.pdf
  • www.cis.temple.edu/jiang/WindowDestroyer.pdf
  • Three key topics
  • Loop, (instance) method, and text/string/array
    processing

10
Simple Output
  • Hello.java,
  • 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
  • Error messages do not always help us understand
    what is wrong
  • File Hello.java line 2
  • Error Hello.java2 ltidentifiergt expected
  • pooblic static void main(String args)
  • Why cant the computer just say You misspelled
    public?

12
  • First lesson
  • Computers cant read minds.
  • Computers dont make mistakes.
  • If the computer is not doing what you want, its
    because YOU made a mistake.

13
  • Java is case-sensitive
  • Public and public are not the same
  • 1 Public class Hello
  • 2 public static void main(String args)
  • 3 System.out.println("Hello, world!")
  • 4
  • 5

14
  • System.out.println A statement to print a line
    of output.
  • pronounced print-linn
  • The use of System.out.println (P93)
  • System.out.println("ltmessagegt")
  • Prints the given message as a line of text.
  • System.out.println(ltnumbergt)
  • Prints the given number as a line of text.

15
  • System.out.println(ltoutput1gt ltoutput2gt
    ltoutput_Lastgt)
  • Performs a output string concatenation and prints
    all as a line of text.
  • System.out.println()
  • Prints a blank line.

16
  • String A sequence of text characters, also
    called message.
  • Start and end with quotation mark characters
  • Examples
  • "hello"
  • "This is a string"
  • "This, too, is a string. It can be very long!"

17
  • 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

18
  • A string can represent certain special characters
    by preceding them with a backslash \ (this is
    called an escape sequence, p89).
  • \t tab character
  • \n newline character
  • \" quotation mark character
  • \\ backslash character
  • Example
  • System.out.println("Hello!\nHow are \"you\"?")

19
  • What is the output of each of the following
    println statements?
  • System.out.println("\ta\tb\tc")
  • System.out.println("\\\\")
  • System.out.println("'")
  • System.out.println("\"\"\"")
  • System.out.println("C\nin\the downward spiral")
  • Write a println statement to produce the
    following line of output (space counted)
  • / \ // \\ /// \\\

20
  • What a println statement will generate the
    following output (one statement only)?
  • This program prints a
  • quote from the Gettysburg Address.
  • "Four score and seven years ago,
  • our 'fore fathers' brought forth on this
    continent
  • a new nation."
  • What a println statement will generate the
    following output?
  • A "quoted" String is
  • 'much' better if you learn
  • the rules of "escape sequences."
  • Also, "" represents an empty String.
  • Don't forget to use \" instead of " !
  • '' is not the same as "

21
  • comment A note written in the source code to
    make the code easier to understand (p104).
  • Comments are not executed when your program runs.
  • Most Java editors show your comments with a
    special color.
  • Comment, general syntax
  • / ltcomment text may span multiple linesgt /
  • or,
  • // ltcomment text, on one linegt
  • Examples
  • / A comment goes here. /
  • / It can even span
  • multiple lines. /
  • // This is a one-line comment.

22
  • 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 or function.
  • inside methods, to explain the complex pieces
    of code.

23
  • Comments provide important documentation.
  • Comments provide a simple description of what
    each class, method, etc. is doing.
  • Later programs will span hundreds or thousands of
    lines, split into many classes and methods.
  • When multiple programmers work together, comments
    help one programmer understand the other's code.

24
Simple Input
  • Sample Program, P15
  • http//www.cis.temple.edu/jiang/1068FirstProgram.
    pdf

25
Variable
  • A piece of your computer's memory that is given a
    name and type and can store a value.
  • Usage
  • compute an expression's result
  • store that result into a variable
  • use that variable later in the program

26
  • To use a variable, it must be declared.
  • Variable declaration syntax (P51)
  • lttypegt ltnamegt
  • Convention Variable identifiers follow the same
    rules as method names.
  • Examples
  • int xdouble myGPA
  • int varName

27
  • Declaring a variable sets aside a piece of memory
    in which you can store a value.
  • int x
  • int y
  • Inside the computer
  • x ? y ?
  • (You know! The memory has an uncertain value.)?

28
  • 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 void main
  • double salary
  • Conventions for naming in Java (which we will
    follow)
  • classes capitalize each word (ClassName)?
  • everything else capitalize each word after the
    first (myLastName)?

29
  • Name, p103
  • Begin with a-Z, _, or
  • Contain only a-Z, 0-9, _, and
  • No keyword
  • Case distinct
  • punctuate, capital letter or _, page 104

30
  • Examples
  • legal susan second_place _myName TheCure ANSWE
    R_IS_42 variable method1 myMethod name2
  • illegal meu 49er question?
    side-swipe hi there ph.d jim's 2milk suzy_at_yaho
    o.com

31
  • 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.

32
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 simple data
    types for numbers, text characters, and logic.
  • class types type of objects, coming soon!

33
  • 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?

34
  • Temperature
  • Sum of a group of integers
  • Average of a group of integers
  • Number of seconds left in a game

35
  • Lesson two
  • Are you able to handle the data that is out of
    the original plan?
  • What a kind (type) of data is in use?
  • Should it be changed to new type?
  • What is the new type?

36
  • Discrete Types
  • byte
  • short
  • int
  • long

Continuous Types float double
Non-numeric Types boolean char
37
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 gt 4.29 million
long ,-2,-1,0,1,2, 8 gt 18 quintillion
float 0.0, 10.5, -100.7 32
double 0.0, 10.5, -100.7 64
38
Arithmetic (Use of variables)
  • 17/3?
  • http//www.cis.temple.edu/jiang/Variable.pdf

39
  • Assignment statement A Java statement that
    stores a value into a variable.
  • Variables must be declared before they can be
    assigned a value.
  • Assignment statement syntax
  • ltvariablegt ltexpressiongt
  • Examples
  • x 2 4 x 8 myGPA 3.25
  • myGPA 3.25

40
  • A variable can be assigned a value more than
    once.
  • Example
  • int xx 3System.out.println(x) // 3x
    4 7System.out.println(x) // 11

41
  • Once a variable is assigned a value, it can be
    used in any expression.
  • int x
  • x 2 4
  • y x 3
  • System.out.println(x 5 - 1)
  • The above has output equivalent to
  • System.out.println(8 5 - 1)
  • What happens when a variable is used on both
    sides of an assignment statement ?
  • int x
  • x 3
  • x x 2 // what happens?

42
  • ERROR Declaring two variables with the same name
  • Exampleint xint 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

43
  • The assignment statement is not an algebraic
    equation!
  • ltvariablegt ltexpressiongt means
  • "store the value of ltexpressiongt into ltvariablegt
  • Some people read x 3 4 as
  • "x gets the value of 3 4"
  • ERROR 3 1 2 is an illegal statement,
    because 3 is not a variable.
  • ERROR a 1 2 is an illegal statement,
    because the expression is incomplete.

44
  • A variable can only store a value of its own
    type.
  • Example
  • int x x 2.5 // ERROR x can only store
    int
  • An int value can be stored in a double variable.
    Why?
  • Type compatibility The value is converted into
    the equivalent real number (p64).
  • Example
  • double myGPA myGPA 2.0
  • myGPA 2

45
double
float
long
int
boolean
short
char
byte
46
  • Manipulating data via expressions
  • Expression A data value or a set of operations
    that produces a value.
  • Examples
  • 1 4 3
  • 3
  • "CSE142"
  • (1 2) 3 4

47
  • Arithmetic operators we will use
  • addition
  • - subtraction or negation
  • multiplication
  • / division
  • modulus, a.k.a. remainder

48
  • When Java executes a program and encounters an
    expression, the expression is evaluated (i.e.,
    computed).
  • Example 3 4 evaluates to 12
  • System.out.println(3 4) prints 12 (after
    evaluating 3 4)?
  • How could we print the text 3 4?

49
  • When dividing integers, the result is also an
    integer the quotient.
  • Example 17 / 3 evaluates to 5, not 5.666666
    (truncate the decimal part)?
  • Examples
  • 35 / 5 is 7
  • 84 / 10 is 8
  • 156 / 100 is 1
  • 24 / 0 is illegal (what do you think happens?)

50
  • The modulus computes the remainder from a
    division of integers.
  • Example 14 4 is 2
  • 1425 27 is 21
  • 3 52
  • 4 ) 14 27 ) 1425
  • 12 135
  • 2 75
  • 54
  • 21
  • What are the results of the following
    expressions?
  • 45 6
  • 4 2
  • 8 20
  • 11 0

51
  • What expression obtains (ChangeMaker.java, P77)
  • the last digit (units place) of a number?
  • Example From 230857, obtain the 7.
  • the last 4 digits of a Social Security Number?
  • Example From 658236489, obtain 6489.
  • the second-to-last digit (tens place) of a
    number?
  • Example From 7342, obtain the 4.
  • the part of a number rounded off to the nearest
    hundredth?
  • Example From 73.424, obtain the 73.42.
  • From 73.425, obtain the 73.42.
  • the part of a number rounded up to the nearest
    hundredth?
  • Example From 73.424, obtain the 73.42.
  • From 73.425, obtain the 73.43.

52
  • Precedence Order in which operations are
    computed in an expression.
  • Operators on the same level are evaluated from
    left to right.
  • Example 1 - 2 3 is 2 (not -4)?
  • Spacing does not affect order of evaluation.
  • Example 13 4-2 is 11

53
  • 1 2 3 5 / 4
  • \_/ 2 3 5 / 4
  • \_/ 2 15 / 4
  • \___/ 2 3
  • \________/ 5
  • 1 2 / 3 5 - 4
  • \_/ 1 0 5 - 4
  • \___/ 1 0 - 4
  • \______/ 1 - 4
  • \_________/ -3

54
  • When an operator is used on an integer and a real
    number, the result is a real number (Type
    compatibility, p64).
  • Examples
  • 4.2 3 is 12.6 1 / 2.0 is 0.5
  • Type cast (p65)
  • Examples
  • (int)4.2 is 4
  • (double)17 is 17.0
  • 7 / 3 1.2 3 / 2
  • \_/ 2 1.2 3 / 2
  • \___/ 2.4 3 / 2
  • \_/ 2.4
    1
  • \________/ 3.4
  • Notice how 3 / 2 is still 1 above, not 1.5.

55
  • 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 - 1 causes a compiler error. Why?

56
  • Write a program to print out the following
    output.
  • Use math expressions to calculate the last two
    numbers.
  • Your grade on test 1 was 95.1
  • Your grade on test 2 was 71.9
  • Your grade on test 3 was 82.6
  • Your total points 249.6
  • Your average 83.2

57
  • The computer internally represents real numbers
    in an imprecise way.
  • Example
  • System.out.println(0.1 0.2)
  • The output is 0.30000000000000004!

58
  • ints are stored in 4 bytes (32 bits)
  • In 32 bits, we can store at most 232 different
    numbers
  • What happens if we take the largest of these, and
    add 1 to it?

59
  • ERROR!
  • This is known as overflow trying to store
    something that does not fit into the bits
    reserved for a data type.
  • http//en.wikipedia.org/wiki/Arithmetic_overflow
  • Overflow errors are NOT automatically detected!
  • Its the programmers responsibility to prevent
    these.
  • The actual result in this case is a negative
    number.

60
  • int n 2000000000
  • System.out.println(n n)
  • // output -1651507200

61
  • the result of nn 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.

62
  • What happens if we create a double value of 1,
    and then keep dividing it by 10?
  • Answer eventually, it becomes 0.
  • This is known as underflow a condition where a
    calculated value is smaller than what can be
    represented using the number of bytes assigned to
    its type
  • http//en.wikipedia.org/wiki/Arithmetic_underflow
  • Again, Java does not detect this error its up
    to the programmer to handle it.

63
  • Legal assignment
  • Left is a single variable
  • Right is a legal expression
  • Prefix and postfix increment/decrement, p79
  • Combined assignment, p73
  • Initialization Declaration, p57
  • Constants (i.e., final), P60

64
  • Shorthand Equivalent longer version
  • ltvariablegt ltvariablegt ltvariablegt 1
  • ltvariablegt-- ltvariablegt ltvariablegt - 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

65
  • after executing
  • int m 4
  • int result 3 (m)
  • result has a value of 15 and m has a value of 5
  • after executing
  • int m 4
  • int result 3 (m)
  • result has a value of 12 and m has a value of 5

66
  • Java has several combined operators that allow
    you to quickly modify a variable's value.
  • Shorthand Equivalent longer version
  • ltvariablegt ltexpgt ltvariablegt ltvariablegt
    (ltexpgt)
  • ltvariablegt - ltexpgt ltvariablegt ltvariablegt -
    (ltexpgt)
  • ltvariablegt ltexpgt ltvariablegt ltvariablegt
    (ltexpgt)
  • ltvariablegt / ltexpgt ltvariablegt ltvariablegt /
    (ltexpgt)
  • ltvariablegt ltexpgt ltvariablegt ltvariablegt
    (ltexpgt)
  • Examples
  • x 3 - 4 // x x (3 - 4)
  • gpa - 0.5 // gpa gpa (0.5)
  • number 2 // number number (2)

67
  • A variable can be declared and assigned an
    initial value in the same statement.
  • Declaration/initialization statement syntax
  • lttypegt ltnamegt ltexpressiongt
  • Examples
  • double myGPA 3.95 int x (11 3) 12

68
  • It is legal to declare multiple variables on one
    line
  • lttypegt ltnamegt, ltnamegt, ..., ltnamegt
  • Examples
  • int a, b, c
  • double x, y
  • It is also legal to declare/initialize several at
    once
  • lttypegt ltnamegt ltexpressiongt , ..., ltnamegt
    ltexpressiongt
  • Examples
  • int a 2, b 3, c -4 double grade 3.5,
    delta 0.1
  • NB The variables must be of the same type.

69
  • To avoid confusion, always name constants (and
    variables).
  • area PI radius radius
  • is clearer than
  • area 3.14159 radius radius
  • Place constants near the beginning of the
    program, CircleCalculation2.java, p108.
  • http//www.cis.temple.edu/jiang/CircleCalculation
    2.pdf

70
  • 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
  • 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.

71
  • Syntax
  • public static final Variable_Type ltnamegt
    ltConstantgt
  • Examples
  • public static final double PI 3.14159
  • public static final String MOTTO "The customer
    is always right."
  • By convention, uppercase letters are used for
    constants.

72
  • Swap.java
  • http//www.cis.temple.edu/jiang/Swap.pdf
  • Payroll.java
  • http//www.cis.temple.edu/jiang/Payroll.pdf

73
  • Math.PI, Math.pow, Math.sqrt, etc. (p412)

74
String
  • text processing Two data types involved

char String
Represents individual characters Represents sequences of characters
Primitive type Object type (i.e., not primitive)
Written with single quotes Written with double quotes
e.g. T t 3 \n e.g. We the people 1. Twas brillig, and the slithy toves\n T
75
  • char A primitive type representing single
    characters. P52.
  • Individual characters inside a String are stored
    as char values.
  • Literal char values are surrounded with
    apostrophe(single-quote) marks, such as 'a' or
    '4' or '\n' or '\''
  • Example, p67.
  • char letter 'S'
  • System.out.println(letter) // prints S
  • System.out.println((int)letter) // prints 83,
  • // explained on p932

76
  • Most programming languages use the ASCII
    character set.
  • Java uses the Unicode character set which
    includes the ASCII character set.
  • The Unicode character set includes characters
    from many different alphabets (but you probably
    won't use them).

77
  • String an object type for representing
    sequences of characters
  • Sequence can be of length 0, 1, or longer
  • Each element of the sequence is a char
  • We write strings surrounded in double-quotes
  • We can declare, initialize, assign, and use
    String variables in expressions just like other
    data types
  • String s Hello, world\n // declare, init
  • System.out.println(s) // use value
  • s s I am your master\n // concatenate
  • // and assign

78
  • Unlike primitive types, String can have methods,
    P86.
  • Here is a list of methods for strings

79
  • Let s be a variable of type String
  • General syntax for calling a String method
  • s.ltmethodgt(ltargsgt)
  • Some examples
  • String s Cola
  • int len s.length() // len 4
  • char firstLetter s.charAt(0) // C
  • int index s.indexOf(ol) // index 1
  • String sub s.substring(1,3) // ol
  • String up s.toUpperCase() // COLA
  • String down s.toLowerCase() // cola

80
  • Displaying message
  • Input P116-118
  • converting a string to number, p123
  • Output P121-122
  • converting a number to string
  • http//www.cis.temple.edu/jiang/Payroll2.pdf

81
Summary of programs in discussion
  • Welcome.java
  • Welcome.java
  • Hello.java
  • Exercises (slide 17-18, 49, 54)
  • FirstProgram.java
  • Variable.java
  • ChangeMaker.java
  • CircleCalculation2.java
  • Swap.java
  • Payroll.java
  • Payroll2.java (a similar program
    ChangeMakerWindow.java)

82
Summary of Concepts
  • Running environment and execution of program (see
    lab work)
  • Template of java program, i.e., file, class, and
    main (see in lab work)
  • Program debug (memory tracking)
  • println and print (P93), escape sequence (P89)
  • Input via keyboard and plain text output (P96-97)
  • I/O via JOptionPane (showInputDialog P116-8,
    showMessageDialog P121-2)
  • Variable (P50-1), name (P55, P103), assignment
    (P55), declaration (P51), type (P52),
    initialization (P57)
  • Constants (P60), type compatibility (P63-4) and
    type cast (P65-66)
  • String, its conversion to number P123 and vice
    versa (concatenation P82)
  • Arithmetic operators (e.g., , P68), precedence
    order (P72)
  • Imprecision (round-off error), and overflow
    (online materials)
  • Prefix and postfix increment/decrement (P78,79),
    combined assignment (P73)
  • Math class, P410-413

83
Other materials (FYI, not required for test)
  • Printf (p101)
  • Delimiters for input (p99)
  • Windows program (p125)
  • http//www.cis.temple.edu/jiang/ChangeMakerWindo
    w.pdf
Write a Comment
User Comments (0)
About PowerShow.com