Java basics - PowerPoint PPT Presentation

1 / 83
About This Presentation
Title:

Java basics

Description:

Purpose: display a quotation in a console window. public class ... in double quotes ... – PowerPoint PPT presentation

Number of Views:167
Avg rating:3.0/5.0
Slides: 84
Provided by: jimco60
Category:
Tags: basics | java | quotation

less

Transcript and Presenter's Notes

Title: Java basics


1
Java basics
  • Chapter 2 (part 1 of 2)
  • Spring 2007
  • CS 101
  • Aaron Bloomfield

2
DisplayForecast.java
  • // Authors J. P. Cohoon and J. W. Davidson
  • // Purpose display a quotation in a console
    window
  • public class DisplayForecast
  • // method main() application entry point
  • public static void main(String args)
  • System.out.print("I think there is a world
    market for")
  • System.out.println(" maybe five
    computers.")
  • System.out.println(" Thomas Watson, IBM,
    1943.")

// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
Three comments
Three statements make up the action of method
main() Method main() is part of class
DisplayForecast
A method is a named piece of code that performs
some action or implements a behavior
An application program is required to have a
public static void method named main().
public, static, and void are keywords. They
cannot be used as names public means the method
is shareable
We will discuss static and void later
Java allows a statement to be made up of multiple
lines of text Semicolons delimit one statement
from the next
A class defines an object form. An object can
have methods and attributes Keyword class
indicates a class definition follows
A class like a method must have a name
A class like a method must have a name
Programs are read by people make sure they are
readable. Use whitespace, comments, and
indentation to aid understanding
// indicates rest of the line is a
comment Comments are used to document authors,
purpose, and program elements
3
Indentation
  • // Authors J. P. Cohoon and J. W. Davidson
  • // Purpose display a quotation in a console
    window
  • public class DisplayForecast
  • // method main() application entry point
  • public static void main(String args)
  • System.out.print("I think there is a world
    market for")
  • System.out.println(" maybe five
    computers.")
  • System.out.println(" Thomas Watson, IBM,
    1943.")

Method main() is part of DisplayForecast
Statements are part of method main()
Indentation indicates subcomponents
4
Good whitespacing
  • // Authors J. P. Cohoon and J. W. Davidson
  • // Purpose display a quotation in a console
    window
  • public class DisplayForecast
  • // method main() application entry point
  • public static void main(String args)
  • System.out.print("I think there is a world
    market for")
  • System.out.println(" maybe five
    computers.")
  • System.out.println(" Thomas Watson, IBM,
    1943.")

Whitespace
Whitespace separates program elements Whitespace
between program elements is ignored by Java
5
Bad whitespacing
  • The same program without any whitespacing or
    comments
  • public class DisplayForecast2 public static
    void main (String args) System.out.print("I
    think there is a world market for")
    System.out.println(" maybe five computers.")
    System.out.println(" Thomas Watson, IBM,
    1943.")

6
A whitespacing aside IOCCC
  • The International Obfuscated C Code Contest
  • Online at http//www.ioccc.org
  • C has very terse syntax
  • So the contest tries to make it terser!
  • One common method is by modifying the whitespace

7
A whitespacing aside IOCCC
X X
X X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X X X
XX X X XX X X
XXX X XXXXXXXXX X XXX
X X XXX X XXXX XXXX X XXX
X X XXXX X XX ainma() archa XX X XXXX
X X XXXX X oink9,igpa, X
XXXX X X XXXXXX atinlaetcharga(),iocccwa
XXXXXX X X XXXX ,apca'A',owla'a',umna2
6 XXXX X X XXX orfa(
(atinla1)(!((( XXX X X XX
atinla-apca)(apcaumna-atinla) XX X X
X gt0)((atinla-owla)(owlaumna- X X X
atinla)gt0))) utcharpa(atinla), X X
X atinlaetcharga()) orfa( atinla1 X X X
X ) orfa( igpaoink ,iocccwa( X X X
X (atinla- XXX apca)( XXX apcaumna- X X
X atinla)gt0) XXX XXX (((( X X
atinla-apca XXXXX XXXXXXX XXXXX )(apca X X
umna-atinla XXXXXX )gt0) XXXXXX ((atinla- X X
owla)(owla XXXX umna- XXXX atinla)gt0)) X
X "-Pig-" XX "Lat-in" XX "COb-fus"
X X "ca-tion!!" X (((atinla- X
apca)(apca X X umna-atinla) X gt0)?atinla-
X apcaowla X X atinla)-owla X
-'-')((igpa X oink)!(( X X igpa)'w')
X )! X (( X igpa X )owla) X X
(igpa)(( X ( XXX XXX X atinla-apca
X X )(apca X umna XXX - XXX X
atinla)gt0) X X ?atinla- X apca XXX XXX owla
X atinla), X X atinla X X X
X etcharga()) X X orfa( X
atinlaiocccwa?(( X (atinla- X X owla)(owla
X umna-atinla)gt0 X )?atinla- X X owlaapca
X atinla) X atinla ((( X X
atinla-apca) X (apcaumna- X atinla)gt0)( X X
(atinla-owla) X (owla X umna-atinla)gt X
X 0)) utcharpa( XX XX atinla),atinla X
X etcharga()) XXXXXXX orfa(igpa0, X
X igpaoink igpa utcharpa( X
X (igpa))) orfa( (atinla1)(!((( X X
atinla-apca )(apca X X
umna- XXXXX XXXXX atinla)gt0 X X
)(( XXXXX atinla- X XX
owla)( owlaumna- XX XX
atinla)gt0))) utcharpa XX XX
(atinla),atinla XX XX
etcharga()) XX XXXX
XXXX XXXXXXXXX
a(X)//X- a(X)//X- -1FX- -1FX-
-1F// -1F// charz"charz","a(
X)//X-","-1FX-","-1F//","9999999999
- ", "int q,i,j,k,X,O0,HS(x)intxXXOO
x1?x2XOx1L(n)for(", "zi1n97
ilt4i)M(256),s(i),M(128),s(i),M(64),NX8O8
s(R)charrz", "Rfor(qQr)P(r)q(Q,P
(44))M(m)P(9)i-2P(Xm?88Om?4832)P(", "9)
y(A)for(j8j)Aw--j(q0)e(W,Z)for(i-
iqilt9q)y(W(1ltlti", "Z))R()for(kJJ-4
8-40k)e(wk--,XO)main(u,v)charva(q1)b
(1)", "c(1)J--u?O?Jv153Xultlt57-vuy
(X)K40qq?e(O,X),q(K''),e(X", ",O),R(),O1
ltlt--iJJ-48(XO0)--L(q0)for(s(i0)qilt12
)s(i),igt4N", "s(q12)P(48)P('')P(59)Nq
0L(1)for(i5ilt13)s(i),NL(2)",0 b(X)/
/X- b(X)//X- -1FX- -1FX- -1F
// -1F// int q,i,j,k,X,O0,HS(x)intxX
XOOx1?x2XOx1L(n)for( zi1
n97ilt4i)M(256),s(i),M(128),s(i),M(64),NX8
O8s(R)charrz Rfor(qQr)P(r)q(Q
,P(44))M(m)P(9)i-2P(Xm?88Om?4832)P( 9)
y(A)for(j8j)Aw--j(q0)e(W,Z)for(i-i
qilt9q)y(W(1ltlti Z))R()for(kJJ-48-4
0k)e(wk--,XO)main(u,v)charva(q1)b(1)
c(1)J--u?O?Jv153Xultlt57-vuy(X)K4
0qq?e(O,X),q(K''),e(X ,O),R(),O1ltlt--iJJ
-48(XO0)--L(q0)for(s(i0)qilt12)s(i),igt
4N s(q12)P(48)P('')P(59)Nq0L(1)for(i
5ilt13)s(i),NL(2) c(X)//X- c(X)//X
- -1FX- -1FX- -1F// -1F//
define X define XX define XXX define
XXXX define XXXXX define XXXXXX define
XXXXXXX define orfa for define
XXXXXXXXX define archa char define ainma
main define etcharga getchar define utcharpa
putchar
define _ -Flt00--F-OO-- int F00,OO00main()F
_OO()printf("1.3f\n",4.-F/OO/OO)F_OO()
_-_-_-_ _-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-
_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-
_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-
_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-
_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_
_-_-_-_
include ltstdio.hgt define Q rRp-'0'while(
define B breakcase chars"Qjou!s\\311-g\\311
-n\\311-c\\-q-mamO1JBHmBQ-aP1JO1HBQltnbj\
o)gps)ltlttxjudi)maQdbtf!sfuvsoltaQefgbvmu
aQltm,,aCQltcsfblabQltaN2!Q\ \ndbtf!aP2QmgtaP2Qlta!
D12J!JGJHJOJQJFJSJJJMHSHD12D12N3!N4\nJUJTUQmgtaP4
HCT\ Qs\\q,,gtm,2ltmgtaP4HCSD12N1\nJNQmgts\\..qaHC
NHbGN1!D32P3RN1UP1D12JPQUaP1H\ RPN4\nQltg\\(aP3
Q(gtaP2Q,2ltn\\(aP3Q(gtaP4HbOD12D12N2!N3\nJVP3Q,,lt
jg)aP3Qgtn\ \\(aP3Q(mgtg\\(aP3Q(ltfmtf!m,,aHCQN1
!N1\nJQqsjoug)eo-aP1QaHbQqvut)\ aP1QaHbF
N1\nQmgtaHCVP3Qgtbupj)hfut)caHbJD12JON1!Qjg)
aLN1UP1D12JIQUa\ P1HLIQmgtaN2!N2\nP2Qltfmtf!m,,aH
CMN1!N2gtP2QgtaN2\nP2Hbdd!b/d"kchar
R499 main(c,v)charvcharp,r,qfor(qs
qq)qgt' '(q)--FILEifopen(v 1,"r"),of
open(q-3,"w")for(psp)switch(p)B'M'Q(kf
getc(i))!EOF k!p)rkif(kEOF)fputs("\
n",o)fclose(o)return system(q-6)r0 B'P'whil
e(p!'')fputc(p,o)B'O'Qr)fputc(r,o)p--B
'C'k0Q kltp-'0' )(rfgetc(i),k)r0
B'I'k pif(Rk)goto G B'G'k
pGpswhile( p!''p1!
k)ppB'N'Rp-'0'0
8
Identifiers
  • Identifiers are names for variables, classes,
    etc.
  • Good ones are compact, but inidicate what they
    stand for
  • radius, width, height, length
  • Bad ones are either too long
  • theRadiusOfTheCircle
  • theWidthOfTheBoxThatIsBeingUsed
  • the_width_of_the_box_that_is_being_used
  • Or too short
  • a, b, c, d, e
  • Good identifiers will help the graders understand
    your program!

9
Keywords
  • Some words are reserved, and cant be used as
    identifiers

// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
// Authors J. P. Cohoon and J. W. Davidson //
Purpose display a quotation in a console
window public class DisplayForecast //
method main() application entry point public
static void main(String args)
System.out.print("I think there is a world market
for") System.out.println(" maybe five
computers.") System.out.println(" Thomas
Watson, IBM, 1943.")
10
Capitalization
  • Case matters!
  • public ? Public ? PUBLIC
  • This is different than FORTRAN and BASIC
  • This is the same as C/C
  • You can use Public as a identifier
  • Not recommended, though!

11
Statements
  • A statement in Java is (usually) a single line
  • Example System.out.println (Hello world!)
  • All statements must end with a semi-colon
  • That tells Java that the statement is finished

12
A bit of humor1989 ComputerAdvertisement
Guess the price!
13
Variables
14
Defining variables
  • Weve seen variables before in math
  • y mx b
  • Here y, m, x, and b can hold any value
  • To store things in a computer program, we also
    use variables
  • Example
  • int x 5
  • Visualization
  • This defines an integer variable with value 5
  • The variable is x
  • The type is int

15
More on variables
  • An integer variable can only hold integers
  • In other words, it cant hold 4.3
  • To hold floating point values, we use the double
    type
  • double d 4.3
  • The variable is d
  • The type is double

16
Primitive variable assignment
  • Assignment operator
  • Allows the memory location for a variable to be
    updated
  • Consider
  • int j 11
  • j 1985
  • Assignment operator
  • Allows the variable to be updated
  • Consider
  • int j 11
  • j 1985

17
Primitive variable assignment
  • Consider
  • int a 1
  • int aSquared a a
  • a 5
  • aSquared a a
  • Consider
  • int i 0
  • i i 1
  • Consider
  • int asaRating
  • asaRating 400
  • int a 1
  • int aSquared a a
  • a 5
  • aSquared a a
  • int i 0
  • i i 1
  • int asaRating
  • asaRating 400

18
Primitive variable assignment
  • Consider
  • double x 5.12
  • double y 19.28
  • double rememberX x
  • x y
  • y rememberX
  • Consider
  • double x 5.12
  • double y 19.28
  • double rememberX x
  • x y
  • y rememberX
  • Consider
  • double x 5.12
  • double y 19.28
  • double rememberX x
  • x y
  • y rememberX
  • Consider
  • double x 5.12
  • double y 19.28
  • double rememberX x
  • x y
  • y rememberX
  • Consider
  • double x 5.12
  • double y 19.28
  • double rememberX x
  • x y
  • y rememberX
  • Consider
  • double x 5.12
  • double y 19.28
  • double rememberX x
  • x y
  • y rememberX

19
Printing variables
  • To print a variable to the screen, put it in a
    System.out.println() statement
  • int x 5
  • System.out.println (The value of x is x)
  • Important points
  • Strings are enclosed in double quotes
  • If there are multiple parts to be printed, they
    are separated by a plus sign

20
  • public class SolvingABC
  • public static void main(String args)
  • // variable definitions and initializations
  • int a 3
  • int b 12
  • int c 6
  • int d 1
  • // calculate results
  • double result1 d a
  • double result2 c 2 a
  • double result3 d - b / c
  • double result4 c b c
  • double result5 b / 2
  • // display the results
  • System.out.println()

From this weeks lab
Note that I dont show a lot of comments so that
the code will fit on a single slide Also note
all the semi-colons
21
Variable initialization
  • Note that the following
  • int x
  • x 5
  • is (mostly) the same as the following
  • int x 5

22
You can only declare variables once
  • The following code will not work
  • int x 5
  • int x 6
  • Java can have only one variable named x
  • So you cant declare multiple variables with the
    same name
  • (well see ways around this later in the semester)

23
Todays demotivators
24
End of lecture on 22 January 2007
25
Types
26
Primitive variable types
  • Java has 8 (or so) primitive types
  • float
  • double
  • boolean
  • char
  • byte
  • short
  • int
  • long

real numbers
two values true and false
a single character
integer numbers
  • Also the void type, which we will see later
  • Well only be using half of the types in this
    course int, double, boolean, and char

27
Primitive real (floating-point) types
  • A float takes up 4 bytes of space
  • Has 6 decimal places of accuracy 3.14159
  • A double takes up 8 bytes of space
  • Has 15 decimal places of accuracy
    3.14159265358979
  • Always use doubles
  • It will save you quite a headache!

28
Primitive integer types
  • Consider a byte
  • 1 byte 8 bits
  • Each bit has two possibilities 0 or 1
  • 28 256
  • Thus, a byte can have any one of 256 values
  • A Java byte can have values from -128 to 127
  • From -27 to 27-1
  • C/C has unsigned versions Java does not

29
Primitive integer types
30
Increment and decrement operators
  • Increments a number variable by 1
  • --
  • Decrements a numeric variable by 1
  • Consider
  • int i 4 // define
  • i
  • System.out.println(i)
  • System.out.print(i)
  • System.out.println(i)
  • System.out.println(i)
  • Increments a number variable by 1
  • --
  • Decrements a numeric variable by 1
  • Consider
  • int i 4
  • i // increment
  • System.out.println(i)
  • System.out.print(i)
  • System.out.println(i)
  • System.out.println(i)
  • Increments a number variable by 1
  • --
  • Decrements a numeric variable by 1
  • Consider
  • int i 4
  • i
  • System.out.println(i) // display
  • System.out.print(i)
  • System.out.println(i)
  • System.out.println(i)
  • Increments a number variable by 1
  • --
  • Decrements a numeric variable by 1
  • Consider
  • int i 4
  • i
  • System.out.println(i)
  • System.out.print(i) // update then display
  • System.out.println(i)
  • System.out.println(i)
  • Increments a number variable by 1
  • --
  • Decrements a numeric variable by 1
  • Consider
  • int i 4
  • i
  • System.out.println(i)
  • System.out.print(i)
  • System.out.println(i) // display then update
  • System.out.println(i)
  • Increments a number variable by 1
  • --
  • Decrements a numeric variable by 1
  • Consider
  • int i 4
  • i
  • System.out.println(i)
  • System.out.print(i)
  • System.out.println(i)
  • System.out.println(i) // display
  • Increments a number variable by 1
  • --
  • Decrements a numeric variable by 1
  • Consider
  • int i 4
  • i
  • System.out.println(i)
  • System.out.print(i)
  • System.out.println(i)
  • System.out.println(i)

31
Why C was named C
  • The increment operator adds one to the integer
    value
  • Or makes it one better
  • So when Bjarne Stroustrup was making the
    successor to C, he was making a one better
    language

32
Primitive character type
  • All characters have a integer equivalent
  • 0 48
  • 1 49
  • A 65
  • a 97
  • Thus, you can refer to B as A1

33
Primitive boolean type
  • The boolean type has only two values
  • true
  • false
  • There are boolean-specific operators
  • is and
  • is or
  • ! is not
  • etc.
  • Well see those operators in a few slides

34
Carved egg shells (done via laser)
35
Variables must be declared before use
  • The following code will not work
  • x 5
  • System.out.println (x)
  • Java requires you to declare x before you use it

36
Variable initialization
  • Consider the following code
  • int x
  • System.out.println(x)
  • What happens?
  • Error message
  • variable x might not have been initialized
  • Java also requires you to give x a value before
    you use it

37
Constants
  • Consider the following
  • final int x 5
  • The value of x can NEVER be changed!
  • The value assigned to it is final
  • This is how Java defines constants
  • Constants have a specific naming scheme
  • MILES_PER_KILOMETER
  • All caps, with underscores for spaces

38
Expressions
  • What is the value used to initialize expression
  • int expression 4 2 5
  • What value is displayed
  • System.out.println(5 / 2.0)
  • Java rules in a nutshell
  • Each operator has a precedence level and an
    associativity
  • Operators with higher precedence are done first
  • and / have higher precedence than and -
  • Associativity indicates how to handle ties
  • When floating-point is used the result is
    floating point

39
Question on expressions
  • Does the following statement compute the average
    of double variables a, b, and c? Why or why not?
  • double average a b c / 3.0

40
Java operators
  • The following are the common operators for ints
  • - /
  • Division is integer division
  • 6 / 2 yields 3
  • 7 / 2 yields 3, not 3.5
  • Because everything is an int, the answer is an
    int
  • Modulus is
  • Returns the remainder
  • 7 2 yields 1
  • 6 2 yields 0
  • Floats and doubles use the same first four
    operators
  • - /
  • 7.0 / 2.0 yields 3.5
  • 7.0 / 2 yields 3.5
  • 7 / 2.0 yields 3.5
  • 7 / 2 yields 3

41
Java operators
  • Booleans have their own operators
  • is AND
  • Only true when both operands are true
  • true true yields true
  • false true yields false
  • is OR
  • True when either of the operands (or both) are
    true
  • true false yields true
  • false false yields false
  • ! is NOT
  • Changes the value
  • !true yields false
  • !false yields true

42
New York Drivers
43
System.out.println
  • Can print multiple things by using the operator
  • Let int i 7
  • Example System.out.println (i i)
  • Prints i 7
  • Can also have the statement on multiple lines
  • System.out.println (
  • hello world!
  • )
  • But cant have the String on multiple lines
  • System.out.println (
  • hello
  • world!
  • )

44
System.out.println
  • System.out.println (result 3/5)
  • What does it print?
  • result 0
  • System.out.println (result 5 3)
  • What does it print?
  • result 2
  • System.out.println (result 3/5.0)
  • What does it print?
  • result 0.6
  • System.out.println (result 34.0)
  • What does it print?
  • result 34.0
  • System.out.println (result (34.0))
  • What does it print?
  • result 7.0

45
End of lecture on 24 January 2007
46
Methods
47
Functions
  • In Java, functions are called methods
  • Think of mathematical functions
  • sin()
  • cos()
  • tan()
  • They take input (the angle)
  • And produce output (the result)
  • In Java, they are called Math.sin(), Math.cos(),
    etc.
  • Meaning, from the Math library, call the sin()
    method

48
  • import java.util.
  • public class MathFun
  • public static void main(String args)
  • // set up the Scanner object
  • Scanner stdin new Scanner(System.in)
  • // have the user input the values for x and y
  • System.out.print("Enter a decimal number ")
  • double x stdin.nextDouble()
  • System.out.print("Enter another decimal number
    ")
  • double y stdin.nextDouble()
  • double squareRootX Math.sqrt(x)
  • System.out.println ("Square root of " x "
    is "
  • squareRootX)

From this weeks lab
49
Scanner usage
50
Interactive programs
  • Programs that interact with their users through
    statements performing input and output
  • Temperature conversion (coming up shortly)
  • Not interactive Celsius temperature is fixed
  • BMI.java (coming up somewhat less shortly)
  • Not interactive weight and height are fixed

51
Reading in a value from the keyboard
  • We will see this in more detail later in this
    slide set
  • For now (and for lab 2), this is what you need to
    know
  • To read in values from the keyboard, you first
    have to create a Scanner object
  • Dont worry about what an object is, what a
    Scanner is, or about creation of these things
  • Well get to them later
  • To do this, use the following code
  • Scanner stdin new Scanner (System.in)
  • NOT the following code
  • Scanner stdin Scanner.create (System.in)

52
Reading in more values from the keyboard
  • You should have this only once in your program.
  • From then on, when you want to read in a value
    into a variable, use the following
  • int x stdin.nextInt()
  • double d stdin.nextDouble()
  • Or
  • x stdin.nextInt()
  • d stdin.nextDouble()

53
Scanner usage example
  • import java.util.
  • public class ScannerUsage
  • public static void main (String args)
  • Scanner stdin new Scanner (System.in)
  • System.out.println ("Enter first value")
  • int x stdin.nextInt()
  • int y
  • System.out.println ("Enter second value")
  • y stdin.nextInt()
  • int z x y
  • System.out.println ("The sum of " x " and "
  • y " is " z)

54
Program demo
  • ScannerUsage.java
  • Note that all this code is available on the
    website!

55
How to make Java work with the Scanner class
  • In Java 1.5, do aimport java.util.
  • To create a new ScannerScanner stdin new
    Scanner (System.in)

56
Todays demotivators
57
Program Examples
58
Example program temperature conversion
// Purpose Convert a Celsius temperature to
Fahrenheit public class CelsiusToFahrenheit
// main() application entry point public
static void main(String args) // set
Celsius temperature of interest int celsius
28 // convert to Fahrenheit
equivalent int fahrenheit 32 ((9
celsius) / 5) // display result
System.out.println("Celsius temperature")
System.out.println(" " celsius)
System.out.println("equals Fahrenheit
temperature") System.out.println(" "
fahrenheit)
59
Program demo
  • CelsiusToFahrenheit.java

60
Computation
  • Programmers frequently write small programs for
    computing useful things
  • Example body mass index (BMI)
  • Measure of fitness
  • Ratio of persons weight to the square of the
    persons height
  • Weight in is kilograms, height is in meters
  • Person of interest is 4.5 feet and weighs 75.5
    pounds
  • Metric conversions
  • Kilograms per pound 0.454
  • Meters per foot 0.3046

61
Program outline for BMI.java
  • // Purpose Compute BMI for given weight and
    height
  • public class BMI
  • // main() application entry point
  • public static void main(String args)
  • // define constants
  • // set up person's characteristics
  • // convert to metric equivalents
  • // perform bmi calculation
  • // display result

62
BMI.java define constants
// define constants final double
KILOGRAMS_PER_POUND 0.454 final double
METERS_PER_FOOT 0.3046
// define constants final double
KILOGRAMS_PER_POUND 0.454 final double
METERS_PER_FOOT 0.3046
// define constants final double
KILOGRAMS_PER_POUND 0.454 final double
METERS_PER_FOOT 0.3046
63
BMI.java personal characteristics
  • // set up person's characteristics
  • double weightInPounds 75.5 // our persons
    weight
  • double heightInFeet 4.5 // our persons
    height
  • // set up person's characteristics
  • double weightInPounds 75.5 // our persons
    weight
  • double heightInFeet 4.5 // our persons
    height
  • // set up person's characteristics
  • double weightInPounds 75.5 // our persons
    weight
  • double heightInFeet 4.5 // our persons
    height

64
BMI.java convert to metric equivalents
// convert to metric equivalents
double metricWeight weightInPounds
KILOGRAMS_PER_POUND double metricHeight
heightInFeet METERS_PER_FOOT
// convert to metric equivalents
double metricWeight weightInPounds
KILOGRAMS_PER_POUND double metricHeight
heightInFeet METERS_PER_FOOT
// convert to metric equivalents
double metricWeight weightInPounds
KILOGRAMS_PER_POUND double metricHeight
heightInFeet METERS_PER_FOOT
65
BMI.java perform BMI calculation
  • // perform bmi calculation
  • double bmi metricWeight / (metricHeight
    metricHeight)

66
BMI.java display result
// display result System.out.println(
"A person with") System.out.println("
weight " weightInPounds " lbs")
System.out.println(" height " heightInFeet "
feet") System.out.println("has a BMI of "
Math.round(bmi))
  • // display result
  • System.out.println("A person with")
  • System.out.println(" weight "
    weightInPounds " lbs")
  • System.out.println(" height " heightInFeet
    " feet")
  • System.out.println("has a BMI of "
    Math.round(bmi))
  • Operator evaluation depend upon its operands

Math.round(bmi) is 18
67
  • public static void main(String args)
  • // define constants
  • final double KILOGRAMS_PER_POUND 0.454
  • final double METERS_PER_FOOT 0.3046
  • // set up person's characteristics
  • double weightInPounds 75.5 // our persons
    weight
  • double heightInFeet 4.5 // our persons
    height
  • // convert to metric equivalents
  • double metricWeight weightInPounds
    KILOGRAMS_PER_POUND
  • double metricHeight heightInFeet
    METERS_PER_FOOT
  • // perform bmi calculation
  • double bmi metricWeight / (metricHeight
    metricHeight)
  • // display result
  • System.out.println("A person with")
  • System.out.println(" weight "
    weightInPounds " lbs")

68
Program demo
  • BMI.java

69
Common program elements
  • Constant
  • Symbolic name for memory location whose value
    does not change
  • KILOGRAMS_PER_POUND
  • Variable
  • Symbolic name for memory location whose value can
    change
  • weightInPounds

70
Removing your car in snow
  • SnowCar.wmv

71
BMI Calculator
72
Interactive program for BMI
  • Program outline
  • import java.util.
  • // Purpose Compute BMI for user-specified
  • // weight and height
  • public class BMICalculator
  • // main() application entry point
  • public static void main(String args)
  • // defining constants
  • // displaying legend
  • // set up input stream
  • // get person's characteristics
  • // convert to metric equivalents
  • // perform bmi calculation
  • // display result
  • Program outline
  • import java.util.
  • // Purpose Compute BMI for user-specified
  • // weight and height
  • public class BMICalculator
  • // main() application entry point
  • public static void main(String args)
  • // defining constants
  • // displaying legend
  • // set up input stream
  • // get person's characteristics
  • // convert to metric equivalents
  • // perform bmi calculation
  • // display result

73
  • public static void main(String args)
  • // define constants
  • //...
  • // displaying legend
  • System.out.println ("BMI Calculator\n")
  • // set up input stream
  • Scanner stdin new Scanner (System.in)
  • // get person's characteristics
  • System.out.print("Enter weight (lbs) ")
  • double weight stdin.nextDouble()
  • System.out.print("Enter height (feet) ")
  • double height stdin.nextDouble()
  • // convert to metric equivalents
  • double metricWeight weight
    KILOGRAMS_PER_POUND

74
  • import java.util.
  • class BMICalculator
  • public static void main(String args)
  • // define constants
  • final double KILOGRAMS_PER_POUND 0.454
  • final double METERS_PER_FOOT 0.3046
  • // displaying legend
  • System.out.println ("BMI Calculator\n")
  • // set up input stream
  • Scanner stdin new Scanner (System.in)
  • // get person's characteristics
  • System.out.print("Enter weight (lbs) ")
  • double weight stdin.nextDouble()
  • System.out.print("Enter height (feet) ")

75
Program demo
  • BMICalculator.java

76
Scanner API
  • public Scanner(InputStream in) // Scanner()
    convenience constructor for an
  • // InputStream
  • public Scanner(File s) // Scanner() convenience
    constructor for a filename
  • public int nextInt() // nextInt() next input
    value as an int
  • public short nextShort() // nextShort() next
    input value as a short
  • public long nextLong() // nextLong() next
    input value as a long
  • public double nextDouble() // nextDouble()
    next next input value as a double
  • public float nextFloat() // nextFloat() next
    next input value as a float
  • public String next() // next() get next
    whitespace-free string
  • public String nextLine() // nextLine()
    return contents of input line buffer

77
End of lecture on 26 January 2007
78
Casting
79
Casting
  • Consider the following code
  • double d 3.6
  • int x Math.round(d)
  • Java complains (about loss of precision). Why?
  • Math.round() returns a long, not an int
  • So this is forcing a long value into an int
    variable
  • How to fix this
  • double d 3.6
  • int x (int) Math.round(d)
  • You are telling Java that it is okay to do this
  • This is called casting
  • The type name is in parenthesis

80
More casting examples
  • Consider
  • double d 3.6
  • int x (int) d
  • At this point, x holds 3 (not 4!)
  • This truncates the value!
  • Consider
  • int x 300
  • byte b (byte) x
  • System.out.println (b)
  • What gets printed?
  • Recall that a byte can hold values -128 to 127
  • 44!
  • This is the loss of precision

81
More on println()
82
System.out.println()
  • public static void main(String args)
  • System.out.print("I think there is a world
    market for")
  • System.out.println(" maybe five computers.")
  • System.out.println(" Thomas Watson, IBM,
    1943.")
  • Class System supplies objects that can print and
    read values
  • System variable out references the standard
    printing object
  • Known as the standard output stream
  • Variable out provides access to printing methods
  • print() displays a value
  • println() displays a value and moves cursor to
    the next line

83
print() vs. println()
  • What do these statements output?
  • System.out.print (foo)
  • System.out.println (bar)
  • System.out.println ()
  • System.out.println (foo)
  • System.out.println (bar)
  • Output
  • foobar
  • foo
  • bar

84
Escape sequences
  • Java provides escape sequences for printing
    special characters
  • \b backspace
  • \n newline
  • \t tab
  • \r carriage return
  • \\ backslash
  • \" double quote
  • \' single quote

85
Escape sequences
  • What do these statements output?
  • System.out.println("Person\tHeight\tShoe size")
  • System.out.println("")
  • System.out.println("Hannah\t51\"\t7")
  • System.out.println("Jenna\t5'10\"\t9")
  • System.out.println("JJ\t6'1\"\t14")
  • Output
  • Person Height Shoe size
  • Hannah 51" 7
  • Jenna 5'10" 9
  • JJ 6'1" 14

86
What we wish computers could do
Write a Comment
User Comments (0)
About PowerShow.com