Академический Документы
Профессиональный Документы
Культура Документы
Chapter 2 (part 1 of 2)
Spring 2007
CS 101
Aaron Bloomfield
1
DisplayForecast.java
// Authors: J. P. Cohoon and J. W. Davidson
// Purpose: display a quotation in a console window
5
A whitespacing aside: IOCCC
The International Obfuscated C Code
Contest
Online at http://www.ioccc.org
#include
int#define <stdio.h> X
F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO()
XXX -1;F;}/*/ -1;F;}/*/ X
XXX ; orfa(; (atinla+1)&&(!(((
XX atinla-apca)*(apca+umna-atinla) XX
XXX X
X
{ #define
#define Q r=R[*p++-'0'];while(
char*z[]={"char*z[]={","a(X){/*/X=-","-1;F;X=-","-1;F;}/*/","9999999999
X :-| ",
X >=0)+((atinla-owla)*(owla+umna- X X
XXXX 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(*",
#define
#define B ;break;case
XXXXX X X atinla=etcharga()); orfa(; atinla+1; X X
#define XXXXXX_-_-_-_
"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",
char*s="Qjou!s\\311^-g\\311^-n\\311^-c\\::^-q-ma%mO1JBHm%BQ-aP1J[O1HB%[Q<nbj\
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(",
#define XXXXXXX
o)*|gps)<<*txjudi)m*|aQdbtf!::::;sfuvso<aQefgbvmu;aQ<m,,a%CQ<csfbla%bQ<aN2!Q\
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++&",
#define orfa for
_-_-_-_-_-_-_-_-_-_-_-_ X atinla-apca XXXXX XXXXXXX XXXXX )*(apca+
\ndbtf!aP2Q;m>aP2Q<a%!D12J!JGJHJOJQJFJSJJJMHS%HD12D12N3!N4\nJUJT%UQm>aP4HC%T\
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 umna-atinla XXXXXX )>=0) XXXXXX +((atinla- X
#define XXXXXXXXX
_-_-_-_-_-_-_-_-_-_-_-_-_-_
Qs\\q,,^>m,2<m>aP4HC%SD12N1\nJNQm>s\\..q^aHC%NHb%GN1!D32P3%RN1UP1D12JPQUaP1H\
#define archa char
X owla)*(owla+ XXXX
"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-"
umna-
XX "Lat-in"
XXXX atinla)>=0)) X
XX "COb-fus" X
R%PN4\nQ<g\\(aP3Q(^>aP2Q,2<n\\(aP3Q(^>aP4Hb%OD12D12N2!N3\nJVP3Q,,<jg)aP3Q=>n\
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
",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",
#define ainma main X "ca-tion!!"[ X (((atinla- X apca)*(apca+ X
X umna-atinla) X >=0)?atinla- X 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};
\\(aP3Q(^*m>g\\(aP3Q(^<fmtf!m,,aHC%QN1!N1\nJ#Qqsjoug)#&e]o#-aP1Q*aHb%#Qqvut)\
#define etcharga getchar
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ X atinla)-owla X ]-'-')||((igpa== X oink)&&!(*( X
b(X){/*/X=- b(X){/*/X=-
aP1Q*aHb%FN1\nQm>::::aHC%VP3Q>bupj)hfut)c**aHb%JD12JON1!Qjg)a%LN1UP1D12JIQUa\
#define utcharpa putchar X igpa++)='w') X )||! X (*( X igpa X ++)=owla); * X
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
-1;F;X=- -1;F;X=- X (igpa++)=(( X ( XXX XXX X atinla-apca X
P1HL%IQ*m>aN2!N2\nP2Q<fmtf!m,,aHC%MN1!N2>P2Q>aN2\nP2Hbdd!b/d";k;char R[4][99]
X )*(apca+ X umna XXX - XXX X atinla)>=0) X
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
-1;F;}/*/ -1;F;}/*/ X ?atinla- X apca XXX + XXX owla X :atinla), X
;main(c,v)char**v;{char*p,*r,*q;for(q=s;*q;q++)*q>' '&&(*q)--;{FILE*i=fopen(v
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 atinla= X X X X etcharga()) X
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
[1],"r"),*o=fopen(q-3,"w");for(p=s;;p++)switch(*p++){B'M':Q(k=fgetc(i))!=EOF
X ; orfa(
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 atinla=iocccwa?(( X (atinla- X
X owla)*(owla+ X umna-atinla)>=0 X )?atinla- X
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
&&k!=*p)*r++=k;if(k==EOF){fputs("}}\n",o);fclose(o);return system(q-6);}*r=0
[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 owla+apca: X atinla): X atinla; ((( X
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++&
B'P':while(*p!='`')fputc(*p++,o)B'O':Q*r)fputc(*r++,o);p--B'C':k=0;Q k<*p-'0'
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);
)(*r++=fgetc(i),k++);*r=0 B'I':k= *p;if(**R==k)goto G B'G':k= *p;G:p=s;while(
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
X 0)); utcharpa( XX
X =etcharga());
XX atinla),atinla X
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
*p!='$'||p[1]!= k)p++;p++B'N':R[*p-'0'][0]++;}}}
_-_-_-_-_-_-_-_-_-_-_-_-_-_ X igpa=oink; *
,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
igpa; utcharpa( X
X *(igpa++))); orfa(; (atinla+1)&&(!((( 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 atinla-apca
X umna-
)*(apca+
XXXXX XXXXX atinla)>=0 X
X
c(X){/*/X=- c(X){/*/X=-
_-_-_-_-_-_-_-_
-1;F;X=- -1;F;X=-
X )+((
XX owla)*(
XXXXX atinla- X
owla+umna- XX
_-_-_-_
-1;F;}/*/ -1;F;}/*/
XX atinla)>=0))); utcharpa XX
XX (atinla),atinla= XX
} 7
XX etcharga()); } XX
XXXX } XXXX
XXXXXXXXX
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
10
Statements
A statement in Java is (usually) a single line
Example: System.out.println (Hello world!);
11
A bit of humor:
1989 Computer
Advertisement
12
Variables
13
Defining variables
Weve seen variables before in math
y = mx + b
Here y, m, x, and b can hold any value
Example:
int x = 5;
Visualization: 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 cant hold 4.3
The variable is d
The type is double
15
Primitive variable assignment
Assignment operator =
Allows the variable
memory tolocation
be updated
for a variable to be updated
target = expression ;
Consider
int j = 11;
j 1985
11
j = 1985;
16
Primitive variable assignment
Consider
int a = 1; a 1
5
int aSquared = a * a;
a = 5;
aSquared = a * a;
aSquared 25
1
Consider
int i = 0;
i 1
0
i = i + 1;
Consider
int asaRating; asaRating 400
-
asaRating = 400;
17
Primitive variable assignment
Consider
double x = 5.12; x 19.28
5.12
double y = 19.28;
double rememberX = x;
y 19.28
5.12
x = y;
y = rememberX;
rememberX 5.12
18
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
19
public class SolvingABC {
weeks
// variable definitions and initializations
int a = 3;
lab
int b = 12;
int c = 6;
int d = 1;
// calculate results
Note that I dont double result1 = d * a;
show a lot of double result2 = c + 2 * a;
comments so that double result3 = d - b / c;
the code will fit on double result4 = c * b % c;
double result5 = b / 2;
a single slide
// display the results
Also note all the System.out.println();
semi-colons System.out.println("result1 : " + result1);
System.out.println("result2 : " + result2);
System.out.println("result3 : " + result3);
System.out.println("result4 : " + result4);
System.out.println("result5 : " + result5);
System.out.println();
}
}
Variable initialization
Note that the following
int x;
x = 5;
int x = 5;
21
You can only declare variables once
The following code will not work:
int x = 5;
int x = 6;
22
Todays demotivators
23
Types
25
Primitive variable types
Java has 8 (or so) primitive types:
float
real numbers
double
boolean two values: true and false
char a single character
byte
short
integer numbers
int
long
27
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
29
Increment and decrement operators
++
Increments a number variable by 1 i 4
5
6
7
--
Decrements a numeric variable by 1
Consider
int i = 4; // define
++i; // increment
System.out.println(i); // display
System.out.print(++i); // update then display
System.out.println(i++); // display then update
System.out.println(i); // display
30
Why C++ was named C++
31
Primitive character type
All characters have a integer equivalent
0 = 48
1 = 49
A = 65
a = 97
32
Primitive boolean type
33
Carved egg
shells (done
via laser)
34
Variables must be declared before use
The following code will not work:
x = 5;
System.out.println (x);
35
Variable initialization
Consider the following code:
int x;
System.out.println(x);
What happens?
Error message:
variable x might not have been initialized
36
Constants
Consider the following:
final int x = 5;
37
Expressions
What is the value used to initialize expression
int expression = 4 + 2 * 5;
39
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
42
System.out.println
Can print multiple things by using the + operator
Let int i = 7;
Example: System.out.println (i = + i);
Prints i = 7
46
Functions
In Java, functions are called methods
47
import java.util.*;
From this // have the user input the values for x and y
System.out.print("Enter a decimal number: ");
weeks double x = stdin.nextDouble();
System.out.print("Enter another decimal number: ");
lab double y = stdin.nextDouble();
49
Interactive programs
Programs that interact with their users through statements
performing input and output
50
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
int x = stdin.nextInt();
double d = stdin.nextDouble();
Or
x = stdin.nextInt();
d = stdin.nextDouble();
52
Scanner usage example
import java.util.*;
int z = x + y;
System.out.println ("The sum of " + x + " and " +
y + " is " + z);
}
}
53
Program demo
ScannerUsage.java
54
How to make Java work with the Scanner
class
In Java 1.5, do a:
import java.util.*;
55
Todays demotivators
56
Program Examples
57
Example program: temperature
conversion
// Purpose: Convert a Celsius temperature to Fahrenheit
// display result
System.out.println("Celsius temperature");
System.out.println(" " + celsius);
System.out.println("equals Fahrenheit temperature");
System.out.println(" " + fahrenheit);
} 58
}
Program demo
CelsiusToFahrenheit.java
59
Computation
Programmers frequently write small programs for computing
useful things
Metric conversions
Kilograms per pound 0.454
Meters per foot 0.3046
60
Program outline for BMI.java
// Purpose: Compute BMI for given weight and height
// display result
}
}
61
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
62
BMI.java: personal characteristics
weightInPounds 75.5
heightInFeet 4.5
63
BMI.java: convert to metric equivalents
metricWeight 34.2770
64
BMI.java: perform BMI calculation
bmi 18.2439
65
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
66
public static void main(String[] args) {
// define constants
final double KILOGRAMS_PER_POUND = 0.454;
final double METERS_PER_FOOT = 0.3046;
// 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
BMI.java
68
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
69
Removing your car in snow
SnowCar.wmv
70
BMI Calculator
71
Interactive program for BMI
Program outline
import java.util.*;
// defining constants
// displaying legend
// set up input stream
// get person's characteristics
// convert to metric equivalents
// perform bmi calculation
// display result
} 72
}
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 {
// displaying legend
System.out.println ("BMI Calculator\n");
// 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
BMICalculator.java
75
Scanner API
public Scanner(InputStream in) // Scanner(): convenience constructor for an
// InputStream
76
Casting
78
Casting
Consider the following code
double d = 3.6;
int x = Math.round(d);
Java complains (about loss of precision). Why?
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
80
More on println()
81
System.out.println()
Class System supplies objects that can print and read values
System.out.print (foo);
System.out.println (bar);
System.out.println ();
System.out.println (foo);
System.out.println (bar);
Output
foobar
foo
bar
83
Escape sequences
Java provides escape sequences for printing special
characters
\b backspace
\n newline
\t tab
\r carriage return
\\ backslash
\" double quote
\' single quote
84
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
86