Java basics Chapter 2 Spring 2005 CS 101

advertisement
Java basics
Chapter 2
Spring 2005
CS 101
Aaron Bloomfield
1
DisplayForecast.java
// Authors: J. P. Cohoon and J. W. Davidson
// Purpose: display a quotation in a console window
public class DisplayForecast {
Three comments
// 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.");
}
}
// class
Three
An
public,
We
Java
A
Programs
method
indicates
application
will
allows
statements
static,
defines
like
discuss
are
isaa
rest
amethod
statement
and
read
named
program
an
static
ofmake
void
object
the
byand
must
piece
people
line
are
is
up
to
form.
void
required
keywords.
is
be
have
the
ofa
–made
code
later
comment
An
action
make
a object
name
to
that
up
sure
have
They
ofof
performs
method
can
they
a
are
main()
some
public
cannot
multiple
have
readable.
methods
action
static
be
lines
used
void
orof
and
implements
as
text
method
names
attributes
named
a behavior
main().
Comments are used to document authors, purpose,
Method
public
Semicolons
Use
and
whitespace,
program
means
main()
delimit
elements
the
iscomments,
part
method
oneofstatement
is
shareable
and
DisplayForecast
indentation
from the
next
to2 aid
Keyword
class
indicates
aclass
class
definition
follows
understanding
Indentation
// Authors: J. P. Cohoon and J. W. Davidson
// Purpose: display a quotation in a console window
public class DisplayForecast {
Method main() is part of
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.");
}
}
Indentation indicates subcomponents
Statements are
part of method
main()
3
Good whitespacing
// Authors: J. P. Cohoon and J. W. Davidson
// Purpose: display a quotation in a console window
public class DisplayForecast {
Whitespace
// 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 separates program elements
Whitespace between program elements is
ignored by Java
4
Bad whitespacing
 The same program without any whitespacing or comments:
public class DisplayForecast2 { public static void
(String[] args) { System.out.print("I think there
world market for"); System.out.println(" maybe
computers."); System.out.println("
Thomas Watson,
1943."); } }
main
is a
five
IBM,
5
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
6
X
X X
X
X
X
X X
X
X
X
X
X
X
X
A whitespacing aside: IOCCC
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
XX
X
X
XX
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
oink[9],*igpa,
X
XXXX
X
a(X){/*/X=a(X){/*/X=X
XXXXXX atinla=etcharga(),iocccwa XXXXXX
X
XXXX ,apca='A',owla='a',umna=26 XXXX
X
-1;F;X=-1;F;X=- X
X
XXX ; orfa(; (atinla+1)&&(!(((
XXX
X
-1;F;}/*/
-1;F;}/*/ X
XX atinla-apca)*(apca+umna-atinla) XX
X
X
X >=0)+((atinla-owla)*(owla+umnaX
X
char*z[]={"char*z[]={","a(X){/*/X=-","-1;F;X=-","-1;F;}/*/","9999999999
:-| ",
X
atinla)>=0))); utcharpa(atinla),
X
"int q,i,j,k,X,O=0,H;S(x)int*x;{X+=X;O+=O;*x+1?*x+2||X++:O++;*x=1;}L(n){for(*",
X
X atinla=etcharga()); orfa(; atinla+1; X
X
"z[i=1]=n+97;i<4;i++)M(256),s(i),M(128),s(i),M(64),N;X*=8;O*=8;}s(R){char*r=z",
X X ){ orfa(
igpa=oink
,iocccwa=( X X
X X (atinla- XXX apca)*( XXX apca+umna- X X
"[R];for(q&&Q;*r;)P(*r++);q&&(Q,P(44));}M(m){P(9);i-2||P(X&m?88:O&m?48:32);P(",
X atinla)>=0) XXX
XXX
; ((((
X
"9);}y(A){for(j=8;j;)~A&w[--j]||(q=0);}e(W,Z){for(i-=i*q;i<9&&q;)y(W|(1<<i++&",
X atinla-apca XXXXX XXXXXXX XXXXX )*(apca+
X
X umna-atinla XXXXXX )>=0) XXXXXX +((atinla- X
"~Z));}R(){for(k=J[*J-48]-40;k;)e(w[k--],X|O);}main(u,v)char**v;{a(q=1);b(1);",
X owla)*(owla+ XXXX
umnaXXXX atinla)>=0)) X
"c(1);*J=--u?O?*J:*v[1]:53;X|=u<<57-*v[u];y(X);K=40+q;q?e(O,X),q&&(K='|'),e(X",
X
&&"-Pig-"
XX "Lat-in"
XX
"COb-fus"
X
X "ca-tion!!"[ X (((atinlaX apca)*(apca+ X
",O),R(),O|=1<<--i:J[*J-48+(X=O=0)]--;L(q=0);for(s(i=0);q=i<12;)s(i++),i>4&&N",
X umna-atinla) X >=0)?atinlaX apca+owla: X
";s(q=12);P(48);P('}');P(59);N;q=0;L(1);for(i=5;i<13;)s(i++),N;L(2);}",0};
X atinla)-owla X ]-'-')||((igpa== X oink)&&!(*( X
b(X){/*/X=b(X){/*/X=X igpa++)='w') X )||! X (*( X igpa X ++)=owla); * X
X atinla-apca X
-1;F;X=-1;F;X=- X (igpa++)=(( X ( XXX XXX
X )*(apca+
X umna XXX - XXX
X atinla)>=0) X
-1;F;}/*/
-1;F;}/*/ X ?atinla- X apca XXX + XXX owla X :atinla), X
X
atinla=
X
X
X
X etcharga()) X
int q,i,j,k,X,O=0,H;S(x)int*x;{X+=X;O+=O;*x+1?*x+2||X++:O++;*x=1;}L(n){for(*
X
; orfa(
X atinla=iocccwa?(( X (atinlaX
z[i=1]=n+97;i<4;i++)M(256),s(i),M(128),s(i),M(64),N;X*=8;O*=8;}s(R){char*r=z
X owla)*(owla+ X umna-atinla)>=0 X )?atinlaX
X owla+apca:
X
atinla):
X atinla; ((( X
[R];for(q&&Q;*r;)P(*r++);q&&(Q,P(44));}M(m){P(9);i-2||P(X&m?88:O&m?48:32);P(
X atinla-apca)* X (apca+umna- X atinla)>=0)+( X
9);}y(A){for(j=8;j;)~A&w[--j]||(q=0);}e(W,Z){for(i-=i*q;i<9&&q;)y(W|(1<<i++&
X (atinla-owla)* X (owla+
X umna-atinla)>= X
~Z));}R(){for(k=J[*J-48]-40;k;)e(w[k--],X|O);}main(u,v)char**v;{a(q=1);b(1);
X 0)); utcharpa( XX
XX atinla),atinla X
X =etcharga());
XXXXXXX orfa(*igpa=0,
X
c(1);*J=--u?O?*J:*v[1]:53;X|=u<<57-*v[u];y(X);K=40+q;q?e(O,X),q&&(K='|'),e(X
X igpa=oink; *
igpa; utcharpa( X
,O),R(),O|=1<<--i:J[*J-48+(X=O=0)]--;L(q=0);for(s(i=0);q=i<12;)s(i++),i>4&&N
X *(igpa++))); orfa(; (atinla+1)&&(!((( X
X atinla-apca
)*(apca+
X
;s(q=12);P(48);P('}');P(59);N;q=0;L(1);for(i=5;i<13;)s(i++),N;L(2);}
X
umnaXXXXX XXXXX atinla)>=0 X
c(X){/*/X=c(X){/*/X=X
)+((
XXXXX
atinla- X
XX owla)*(
owla+umna- XX
-1;F;X=-1;F;X=XX atinla)>=0))); utcharpa XX
-1;F;}/*/
-1;F;}/*/
XX (atinla),atinla=
XX
XX etcharga()); } XX
XXXX
}
XXXX
XXXXXXXXX
#define X
#define
#define _XX-F<00||--F-OO--;
#include
<stdio.h>
int#define
F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO()
XXX
r=R[*p++-'0'];while(
#define Q
XXXX
{ #define
#define
;break;case
#define B
XXXXX
_-_-_-_
#define XXXXXX
char*s="Qjou!s\\311^-g\\311^-n\\311^-c\\::^-q-ma%mO1JBHm%BQ-aP1J[O1HB%[Q<nbj\
_-_-_-_-_-_-_-_-_
#define
XXXXXXX
o)*|gps)<<*txjudi)m*|aQdbtf!::::;sfuvso<aQefgbvmu;aQ<m,,a%CQ<csfbla%bQ<aN2!Q\
#define
orfa for
_-_-_-_-_-_-_-_-_-_-_-_
\ndbtf!aP2Q;m>aP2Q<a%!D12J!JGJHJOJQJFJSJJJMHS%HD12D12N3!N4\nJUJT%UQm>aP4HC%T\
#define XXXXXXXXX
Qs\\q,,^>m,2<m>aP4HC%SD12N1\nJNQm>s\\..q^aHC%NHb%GN1!D32P3%RN1UP1D12JPQUaP1H\
_-_-_-_-_-_-_-_-_-_-_-_-_-_
#define archa char
R%PN4\nQ<g\\(aP3Q(^>aP2Q,2<n\\(aP3Q(^>aP4Hb%OD12D12N2!N3\nJVP3Q,,<jg)aP3Q=>n\
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
#define ainma main
\\(aP3Q(^*m>g\\(aP3Q(^<fmtf!m,,aHC%QN1!N1\nJ#Qqsjoug)#&e]o#-aP1Q*aHb%#Qqvut)\
#define etcharga getchar
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
#define utcharpa putchar
aP1Q*aHb%FN1\nQm>::::aHC%VP3Q>bupj)hfut)c**aHb%JD12JON1!Qjg)a%LN1UP1D12JIQUa\
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
P1HL%IQ*m>aN2!N2\nP2Q<fmtf!m,,aHC%MN1!N2>P2Q>aN2\nP2Hbdd!b/d";k;char R[4][99]
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
;main(c,v)char**v;{char*p,*r,*q;for(q=s;*q;q++)*q>' '&&(*q)--;{FILE*i=fopen(v
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
[1],"r"),*o=fopen(q-3,"w");for(p=s;;p++)switch(*p++){B'M':Q(k=fgetc(i))!=EOF
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
&&k!=*p)*r++=k;if(k==EOF){fputs("}}\n",o);fclose(o);return system(q-6);}*r=0
B'P':while(*p!='`')fputc(*p++,o)B'O':Q*r)fputc(*r++,o);p--B'C':k=0;Q k<*p-'0'
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
)(*r++=fgetc(i),k++);*r=0 B'I':k= *p;if(**R==k)goto G B'G':k= *p;G:p=s;while(
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
*p!='$'||p[1]!=
k)p++;p++B'N':R[*p-'0'][0]++;}}}
_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_
_-_-_-_
}
7
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 can’t 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.");
}
10
Capitalization
 Case matters!
 public ≠ Public ≠ PUBLIC
 This is different that 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
Variables
13
Defining variables
 We’ve 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;
 This defines an integer variable with value 5
 The variable is x
 The type is int
14
More on variables
 An integer variable can only hold integers
 In other words, it can’t hold 4.3
d
4.3
 To hold floating point values, we use the double type
 double d = 4.3;
 The variable is d
 The type is double
15
Primitive variable assignment
 Assignment operator =
 Allows the variable
memory to
location
be updated
for a variable to be updated
target
=
Name of previously
defined object
 Consider
int j = 11;
j = 1985;
expression ;
Expression t o be
evaluat ed
j
1985
11
16
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;
a
1
5
aSquared
25
1
i
1
0
asaRating
400
17
Primitive variable assignment
 Consider
double x = 5.12;
double y = 19.28;
double rememberX = x;
x = y;
y = rememberX;
x
19.28
5.12
y
19.28
5.12
rememberX
5.12
18
A bit of humor…
19
Printing variables
 To print a variable to the
System.out.println() statement:
screen,
put
it
in
a
 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 {
From this
week’s
lab
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 *
double result2 = c +
double result3 = d double result4 = c *
double result5 = b /
Note that I don’t
show a lot of
comments so that
the code will fit on
a single slide
a;
2 * a;
b / c;
b % c;
2;
// display the results
System.out.println();
System.out.println("result1
System.out.println("result2
System.out.println("result3
System.out.println("result4
System.out.println("result5
System.out.println();
Also note all the
semi-colons
}
}
:
:
:
:
:
"
"
"
"
"
+
+
+
+
+
result1);
result2);
result3);
result4);
result5);
Variable initialization
 Note that the following
 int x;
 x = 5;
 is the same as the following:
 int x = 5;
22
Primitive variable types
 Java has 8 (or so) primitive types:
 float
real numbers
 double
two values: true and false
 boolean
 char
a single character
 byte
 short
integer numbers
 int
 long
 Also the void “type”
 We’ll only be using half of the types in this course: int,
23
double, boolean, and char
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!
24
Primitive integer types

Consider a byte:
0
1
0
0
0
1
0
1


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
25
Primitive integer types
Type
Bytes Minimum value
Maximum value
byte
1
-27=-128
27-1=127
short 2
-215=
-32,768
215-1=
32,767
int
4
-231=-2,147,483,648
231-1=2,147,483,647
long
8
-263=-9,223,372,036,
854,775,808
263-1=9,223,372,036,
854,775,807
26
Increment and decrement operators
 ++
 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);
//
//
//
//
//
//
i
4
5
6
7
define
increment
display
update then display
display then update
display
27
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
28
Why you should get the
extended warranty
29
Primitive character type
 All




characters have a integer equivalent
‘0’ = 48
‘1’ = 49
‘A’ = 65
‘a’ = 97
 Thus, you can refer to ‘B’ as ‘A’+1
30
Primitive boolean type
 The boolean type has only two values:
 true
 false
 There are boolean-specific operators
 && is and
 || is or
 ! is not
 etc.
31
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
32
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
33
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
34
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
35
 When floating-point is used the result is floating point
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;
36
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
37
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
38
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!”
)
;
 Can’t have the String on multiple lines
System.out.println (
“hello
world!”
);
39
System.out.println
 System.out.println (“result:
 What does it print?
 result: 0
 System.out.println (“result:
 What does it print?
 result: 2
 System.out.println (“result:
 What does it print?
 result: 0.6
 System.out.println (“result:
 What does it print?
 result: 34.0
 System.out.println (“result:
 What does it print?
 result: 7.0
“ + 3/5);
“ + 5 % 3);
“ + 3/5.0);
“ + 3+4.0);
“ + (3+4.0));
40
More demotivators
41
Methods
42
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
43
import java.util.*;
public class MathFun {
public static void main(String[] args) {
// set up the Scanner object
Scanner stdin = new Scanner(System.in);
From this
week’s
lab
// 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);
}
}
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
45
Escape sequences
 Java provides escape sequences
characters
 \b
backspace
 \n
newline
 \t
tab
 \r
carriage return
 \\
backslash
 \"
double quote
 \'
single quote
for
printing
special
46
Escape sequences
 What do these statements output?
System.out.println("Person\tHeight\tShoe size");
System.out.println("=========================");
System.out.println("Hannah\t5‘1\"\t7");
System.out.println("Jenna\t5'10\"\t9");
System.out.println("JJ\t6'1\"\t14");
 Output
Person Height Shoe size
=========================
Hannah 5‘1"
7
Jenna
5'10"
9
JJ
6'1"
14
47
System.out
System.out : PrintStream
- destination =
- ...
+ println(String s) : void
+ print(String s) : void
+ ...
Variable System.out gives
access to an output stream
of type PrintStream
The printing destination attribute
for this PrintStream object is the
console window
The behaviors of a PrintStream
object support a high-level view of
printing
48
Selection
The period indicates that we want to select an
individual class member of System
The period indicates that we want to
select an individual class member of out
The method we are calling
System
.
out
.
print
(
" string
"
)
Member out of System is an output
Literal character string that is
stream object automatically
the parameter to print().
associated with the console window
running the application
Class System is defined
in the standard
Method member of out. The execution of member print()
package java.lang
causes its parameter to be displayed to the output stream
49
I/O streams
 System.out
 Prints to standard output
 Equivalent to cout in C++, and print() in C
 System.err
 Prints to standard error
 Equivalent to cerr in C++, and fprintf(stderr) in C
 System.in
 Reads from standard input
 Equivalent to cin in C++, and scanf() in C
50
Program Examples
51
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);
}
}
52
Program demo…
53
Computation
 Programmers frequently write small programs for computing
useful things
 Example – body mass index (BMI)
 Measure of fitness
 Ratio of person’s weight to the square of the person’s
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
55
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
}
}
56
BMI.java: define constants
KILOGRAMS_PER_POUND
0.454
// define constants
final double KILOGRAMS_PER_POUND = 0.454;
final double METERS_PER_FOOT = 0.3046;
METERS_PER_FOOT
0.3046
57
BMI.java: personal characteristics
weightInPounds
75.5
// set up person's characteristics
double weightInPounds = 75.5; // our person’s weight
double heightInFeet = 4.5;
// our person’s height
heightInFeet
4.5
58
BMI.java: convert to metric equivalents
metricWeight
34.2770
// convert to metric equivalents
double metricWeight = weightInPounds *
KILOGRAMS_PER_POUND;
double metricHeight = heightInFeet *
METERS_PER_FOOT;
metricHeight
1.3706
59
BMI.java: perform BMI calculation
// perform bmi calculation
double bmi =
metricHeight);
metricWeight
/
(metricHeight
bmi
*
18.2439
60
BMI.java: display result
bmi
18.2439
// 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));
Math.round(bmi) is 18
Operator evaluation depend upon its operands
61
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 person’s weight
double heightInFeet = 4.5;
// our person’s 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");
System.out.println(" height " + heightInFeet + " feet");
System.out.println("has a BMI of " + Math.round(bmi));
}
Program demo…
63
Beware!!!
64
Common program elements
 Type
 Set of values along with operators that can manipulate
and create values from the set
 Primitive types support numeric, character, logical values
 double and float
 Values with decimals
 byte, short, int, long
 Integers
 char
 Characters (considered numeric)
 boolean
 Logical values
 Basic operators
 + addition
 * multiplication
- subtraction
/ division
65
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
66
Interactive programs
 Programs that interact with their users through statements
performing input and output
 Temperature conversion
 Not interactive – Celsius temperature is fixed
 BMI.java
 Not interactive – weight and height are fixed
67
Support for interactive console programs
 Variable System.in
 Associated with the standard input stream – the keyboard
 Class Scanner
 Makes obtaining input from the keyboard easy
Scanner stdin = new Scanner (System.in);
stdin : Scanner
- source =
- ...
Variable stdin gives Scanner
access to an input stream
Input source attribute for this
Scanner is the keyboard
+ nextDouble() : double
+ ...
Behaviors of a Scanner support 68
high-level view of inputting text
How to make Java work with the Scanner
class
 In Java 1.5, do a:
import java.util.*;
 To create a new Scanner:
Scanner stdin = new Scanner (System.in);
 Do NOT use the following (it won’t work):
Scanner stdin = Scanner.create (System.in);
 This is the big difference between the textbook versions!!!
69
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
70
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;
double metricHeight = height * METERS_PER_FOOT;
// perform bmi calculation
double bmi = metricWeight / (metricHeight * metricHeight);
// display result
//...
}
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): ");
double height = stdin.nextDouble();
// convert to metric equivalents
double metricWeight = weight * KILOGRAMS_PER_POUND;
double metricHeight = height * METERS_PER_FOOT;
// perform bmi calculation
double bmi = metricWeight / (metricHeight * metricHeight);
// display result
System.out.println("A person with");
System.out.println(" weight " + weight + " lbs");
System.out.println(" height " + height + " feet");
System.out.println("has a BMI of " + Math.round(bmi));
}
}
Program demo…
73
An optical illusion
74
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
public boolean hasNext()
// hasNext(): is there a value to next
75
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
76
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”
77
About the assignment statement
 Assign the value 5 to the variable x
 int x;
 x = 5;
 5 = x;
NOT VALID!
 This is not a mathematical equals
 It’s a Java assignment
 The variable you want to copy the value to MUST be on the
left
 The value you want to copy MUST be on the right
 Assignment copies the value on the right to the variable on
78
the left
Today’s demotivators
79
Download