Download 02 helloworld

Document related concepts
no text concepts found
Transcript
1.1 Your First Program
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Why Programming?
Idealized computer. "Please simulate the motion of a system of N
heavenly bodies, subject to Newton's laws of motion and gravity."
Prepackaged software solutions. Great, if it does exactly what you need.
Computer programming. Art of making a computer do what you want.
Ada Lovelace
Analytic Engine
2
Languages
Instead of imagining that our main task is to instruct a computer
what to do, let us concentrate rather on explaining to human
beings what we want a computer to do. - Donald Knuth
Machine languages. Tedious and error-prone.
“Natural” languages. Ambiguous and hard for computer to parse.
High-level programming languages. Acceptable tradeoff.
3
Real newspaper headlines (compiled by Rich Pattis)

Kids Make Nutritious Snacks.

Red Tape Holds Up New Bridge.

Police Squad Helps Dog Bite Victim.

Local High School Dropouts Cut in Half.
(BTW, computers and natural language
processing? Yes, a sub-field! Also,
computational linguistics, digital humanities,
etc.)
4
What’s a Program?
5
Executing a Program
1:
(Comment: Our goal is to find the row of students that has the most
students who have birthdays in August.)
2:
3:
4:
5:
For each row R in your section, do the following:
Let N be the number of students in the current row R.
If N is equal to 0, skip to instruction on line 17.
Otherwise, N is greater than 0 -- do the following steps:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
(Comment: the next section's goal is to count how many students
For each student S in the row, do the following:
Ask if his or her birthday is in August.
If "yes", then add 1 to your count of August-birthdays in this row.
(End of the steps for each student in the row.)
(Comments: the next section's goal is to see if this is larger than
previous best.)
If the count is larger than your maximum-so-far value, then do
the following:
Update your maximum-so-far value to be the count for that row.
Let Row-ID be the name of the student sitting on the aisle.
(End of steps for when count > max-so-far.)
(End of steps for when number of students N is greater than 0.)
(Now, go to the next row! If no more rows, go to next step.)
18: Report the following:
"The row where Row-ID is on the aisle has maximum-so-far August birthdays. That is the most for
any row in my section."
6
Why Java?
Java features.
Widely used.
Widely available.
Embraces full set of modern abstractions.
Variety of automatic checks for mistakes in programs.




James Gosling
http://java.net/jag
Java economy.
Mars rover.
$100 billion,
5 million developers
Cell phones.
Blu-ray Disc.
Web servers.
Medical devices.
Supercomputing.
…







7
Why Java?
Java features.
Widely used.
Widely available.
Embraces full set of modern abstractions.
Variety of automatic checks for mistakes in programs.




Caveat.
There are only two kinds of programming languages: those people
always [gripe] about and those nobody uses. - Bjarne Stroustrup
8
Why Java?
Java features.
Widely used.
Widely available.
Embraces full set of modern abstractions.
Variety of automatic checks for mistakes in programs.




Caveat. No perfect language.
Our approach.
Minimal subset of Java.
Develop general programming skills that are applicable to:
C, C++, C#, Perl, Python, Ruby, Matlab, Fortran, Fortress, …


9
A Rich Subset of the Java Language
Built-In Types
System
Math Library
int
double
System.out.println()
Math.sin()
Math.cos()
long
String
System.out.print()
Math.log()
Math.exp()
char
boolean
System.out.printf()
Math.sqrt()
Math.pow()
Math.min()
Math.max()
Math.abs()
Math.PI
Flow Control
Parsing
if
else
Integer.parseInt()
for
while
Double.parseDouble()
Boolean
Punctuation
Primitive Numeric Types
+
-
*
/
%
++
true
false
{
}
--
>
<
||
&&
(
)
<=
>=
==
,
;
!=
!
String
Arrays
Objects
+
""
a[i]
class
static
length()
compareTo()
new
public
private
charAt()
matches()
a.length
toString()
equals()
new
main()
10
Create, Compile, Execute
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Programming in Java
Programming in Java.
Create the program by typing it into a text editor, and
save it as HelloWorld.java


Read more: page 5 of textbook
/*******************************************
* Prints "Hello, World"
* Everyone's first Java program.
*******************************************/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
HelloWorld.java
12
Programming in Java
Issue for Beginners Using Java.
Confusing! What are those first two lines of code all about?!
For now: think of the program you write as only being the line
“inside” that thing called main
New program? Make a copy of this file HelloWorld.java, and
rename both the file and the class (line 1 of the code)



/*******************************************
* Prints "Hello, World"
* Everyone's first Java program.
*******************************************/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
HelloWorld.java
13
Programming in Java
Some things to note:
Comments:

–
not instructions for the computer, for human readers
–
/* a comment */ or // comment to end of line
Pairs of “delimiters”: {…}

–

“…”
(…)
[…]
Curly-brackets: blocks of code that are one “unit” somehow (more on this later)
Spacing and Indentation: makes code easier for humans to read
/*******************************************
* Prints "Hello, World"
* Everyone's first Java program.
*******************************************/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
HelloWorld.java
14
Programming in Java
Programming in Java.
Create the program by typing it into a text editor, and
save it as HelloWorld.java
Compile it by typing at the command-line:


javac HelloWorld.java
command-line
% javac HelloWorld.java
(or click the Compile button in your IDE)

This creates a Java bytecode file named: HelloWorld.class
15
Programming in Java
Programming in Java.
Create the program by typing it into a text editor, and
save it as HelloWorld.java
Compile it by typing at the command-line:


javac HelloWorld.java

Execute it by typing at the command-line:
java HelloWorld
command-line
% javac HelloWorld.java
% java HelloWorld
Hello, World
(or click the Run button in your IDE)
16
Interactive Development Environments (IDEs)






An IDE is a software tool that:
Includes a “smart” editor for your language
Lets you compile all your Java from within the tool
Lets you run the compiled program from within the tool
Supports debugging
Supports many other programmer needs, especially for large
programs
Example IDEs for Java:
DrJava (for beginners)
Eclipse (powerful!)
Important to know how Java programs are built and run
without using IDEs!
17
18
What you know after Lab 0!





A Java program is created in a .java file.
First line defines the class/program and
the name.
The name of the class must match name of
.java file
Second line defines main() method.
(For now) your program is set of
statements in main().
19
What you know after Lab 0!






A Java statement ends in a semi-colon.
Sometimes statements are grouped inside {
and }.
Curly-brackets must nest properly.
Comments are indicated by // or by /* ... */
How Java treats whitespace.
Indentation and spacing are important of
human readers.
20
What you know after Lab 0!




Data in a running program is stored in a
variable.
Variables have a type (int, double, String).
Variables are declared with a name and
type, and can be initialized.
Literal values can be assigned to variables.
21
What you know after Lab 0!





Methods have a name and invoke some
operation or function on some data.
Example: System.out.println("Hiya!");
Some methods return a value that can be
used.
Example: Math.sqrt(100)
Methods like these are part of Java's
Standard Library.
22
What you know after Lab 0!




Java programs (.java files) are compiled.
This creates a .class file.
The class file contains machine instructions.
To run the program, execute the class file.
23
24
A More Complicated Example (for Lab 0)
// This is a comment at the top of class/program Demo1
public class Demo1 {
public static void main(String[] args) {
// program statements go inside method main
System.out.println("Hello world!");
int x = 3;
System.out.println("The value of variable x is: " + x);
x = x + 3;
System.out.println("Now the value of variable x is: " + x);
// continued….
25
Lab 0 Example continued
double pi = 3.14;
System.out.println("The value of variable pi is: " + pi);
double someValue = Math.sqrt(x);
System.out.println("The sqrt of x is: " + someValue);
System.out.println("The sqrt of 100 is: " + Math.sqrt(100));
String message = "Psst! We said pi is " + pi + "!!!";
System.out.println("Message is: " + message);
}
// we're done!
26
Typical Scenario for Solving Problems with a Program
1.
2.
Gather requirements
Develop high-level approach
1.
2.
3.
3.
4.
5.
Choose language, and then choose IDE
Design test cases (both “positive” and
“negative”)
Iterate until requirements met (maybe
create new requirements!)
1.
2.
3.
6.
Rough break-down of the parts (maybe)
Algorithms
Pseudo-code (maybe)
Write code
Test
Debug (fix)
Use the finished code to solve the problem
at hand
27
Let’s Solve a Problem with a Program!



The book and booksite has many examples:
http://www.cs.princeton.edu/introcs/12types/
Problem 1.2.18: If x and y represent a point (x,y)
in a Cartesian plane, print the distance to the
origin.
– Version 2: find distance from (x1,y1) to (x2,y2)
Problem 1.2.25: Wind chill. Given the temperature
t and wind-speed v, we define the wind chill to be:
w = 35.74 + 0.6215 t - (0.4275 t - 35.75) v0.16
Write a program WindChill.java that reads two
double values t and v and prints out the wind chill.
Use Math.pow(a, b) to compute ab.
28
1.2 Built-In Types of Data
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Built-in Data Types
Data type. A set of values and operations defined on those values.
type
set of values
literal values
operations
char
characters
'A'
'@'
compare
String
sequences of
characters
"Hello World"
"CS is fun"
concatenate
int
integers
17
12345
add, subtract,
multiply, divide
double
floating point
numbers
3.1415
6.022e23
add, subtract,
multiply, divide
boolean
truth values
true
false
and, or, not
30
Basics
Definitions.
Trace.
31
Text
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Text
String data type. Useful for program input and output.
33
Subdivisions of a Ruler
public class Ruler {
public static void main(String[] args) {
String ruler1 = "1";
String ruler2 = ruler1 + " 2 " + ruler1;
String ruler3 = ruler2 + " 3 " + ruler2;
String ruler4 = ruler3 + " 4 " + ruler3;
System.out.println(ruler4);
}
}
"1"
"1 2 1"
"1 2 1 3 1 2 1"
string concatenation
% java Ruler
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
34
Subdivisions of a Ruler
public class Ruler {
public static void main(String[] args) {
String ruler1 = "1";
String ruler2 = ruler1 + " 2 " + ruler1;
String ruler3 = ruler2 + " 3 " + ruler2;
String ruler4 = ruler3 + " 4 " + ruler3;
System.out.println(ruler4);
}
}
% java Ruler
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
35
Integers
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Integers
int data type. Useful for expressing algorithms.
37
Integer Operations
public class IntOps {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
int prod = a * b;
int quot = a / b;
int rem = a % b;
System.out.println(a + " + " + b + " =
System.out.println(a + " * " + b + " =
System.out.println(a + " / " + b + " =
System.out.println(a + " % " + b + " =
}
}
% javac IntOps.java
% java IntOps 1234 99
1234 + 99 = 1333
1234 * 99 = 122166
1234 / 99 = 12
1234 % 99 = 46
1234 = 12*99 + 46
command-line
arguments
"
"
"
"
+
+
+
+
sum);
prod);
quot);
rem);
Java automatically converts
a, b , and rem to type String
38
Reading from the Keyboard (p. 126-127)
public class IntOps {
public static void main(String[] args) {
int a = StdIn.readInt();
int b = StdIn.readInt();
int sum = a + b;
int prod = a * b;
int quot = a / b;
int rem = a % b;
System.out.println(a
System.out.println(a
System.out.println(a
System.out.println(a
Calls to book’s library function
to read an int value from keyboard
+
+
+
+
"
"
"
"
+
*
/
%
"
"
"
"
+
+
+
+
b
b
b
b
+
+
+
+
"
"
"
"
=
=
=
=
"
"
"
"
+
+
+
+
sum);
prod);
quot);
rem);
}
}
• StdIn.readint() and StdIn.readDouble() etc. (see pages 127-127)
• Library methods, just like sqrt() and System.out.println()
• Not standard Java, but created by our textbook authors
• Must have the Java file StdIn.java in same directory as your code
39
Initializing Variables
Q. What happens if I forget to initialize the variable a or b?
Java compiler does not allow this.
Caveat: in other languages, variable initialized to arbitrary value.


Q. What do you mean, arbitrary?
40
Initializing Variables
Q. What happens if I forget to initialize the variable a or b?
Java compiler does not allow this.
Caveat: in other languages, variable initialized to arbitrary value.


Q. What do you mean, arbitrary?
int main( int argc, char *argv[] ) {
int whoops;
printf( "%d\n", whoops );
}
% gcc -o uninit uninit.c
% uninit
-1073746048
uninitialized
variable
C code
41
Floating-Point Numbers
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Floating-Point Numbers
double data type. Useful in scientific applications.
43
Math Library
44
Quadratic Equation
Ex. Solve quadratic equation x2 + bx + c = 0.
b  b 2  4 c
roots 
2
public class Quadratic {

public static void main(String[] args) {
// parse coefficients from command-line
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
// calculate roots
double discriminant = b*b - 4.0*c;
double d = Math.sqrt(discriminant);
double root1 = (-b + d) / 2.0;
double root2 = (-b - d) / 2.0;
}
}
// print them out
System.out.println(root1);
System.out.println(root2);
45
Testing
Testing. Some valid and invalid inputs.
% java Quadratic –3.0 2.0
2.0
1.0
command-line arguments
% java Quadratic –1.0 –1.0
1.618033988749895
-0.6180339887498949 golden ratio
% java Quadratic 1.0 1.0
NaN
NaN
not a number
x2 – 3x + 2
x2 – x - 1
x2 + x + 1
% java Quadratic 1.0 hello
java.lang.NumberFormatException: hello
% java Quadratic 1.0
java.lang.ArrayIndexOutOfBoundsException
46
Booleans
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Booleans
boolean data type. Useful to control logic and flow of a program.
48
Comparisons
Comparisons. Take operands of one type and produce an operand of
type boolean.
49
Leap Year
Q. Is a given year a leap year?
A. Yes if either (i) divisible by 400 or (ii) divisible by 4 but not 100.
public class LeapYear {
public static void main(String[] args) {
int year = Integer.parseInt(args[0]);
boolean isLeapYear;
// divisible by 4 but not 100
isLeapYear = (year % 4 == 0) && (year % 100 != 0);
// or divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
System.out.println(isLeapYear);
}
}
% java LeapYear 2004
true
% java LeapYear 1900
false
% java LeapYear 2000
true
50
Type Conversion
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Type Conversion
Type conversion. Convert from one type of data to another.
Automatic: no loss of precision; or with strings.
Explicit: cast; or method.


52
Random Integer
Ex. Generate a pseudo-random number between 0 and N-1.
public class RandomInt {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double r = Math.random();
String to int (method)
int n = (int) (r * N);
double between 0.0 and 1.0
double to int (cast) int to double (automatic)
System.out.println("random integer is " + n);
}
}
% java
random
% java
random
% java
random
RandomInt 6
integer is 3
RandomInt 6
integer is 0
RandomInt 10000
integer is 3184
int to String (automatic)
53
Summary
A data type is a set of values and operations on those values.
String
text processing.
double, int
mathematical calculation.
boolean
decision making.



Be aware.
Declare type of values.
Convert between types when necessary.
In 1996, Ariane 5 rocket exploded after takeoff
because of bad type conversion.



54
1.3 Conditionals and Loops
CS101: Introduction to Computer Science • Slides adapted from Sedgewick and Wayne • Copyright © 2007 •
Control Flow
Control flow.
Sequence of statements that are actually executed in a program.
Conditionals and loops: enable us to choreograph control flow.


boolean 1
statement 1
true
false
statement 2
statement 1
statement 3
boolean 2
true
statement 2
false
statement 4
statement 3
straight-line control flow
control flow with conditionals and loops
56
If-Else Statement
The if-else statement. A common branching structure.
Check boolean condition.
If true, execute some statements.
Otherwise, execute other statements.



if (boolean expression) {
statement T;
}
can be any sequence
else {
of statements
statement F;
}
if-else syntax
boolean
expression
false
true
statement T
statement F
if-else flow chart
57
If-Else: Leap Year
If-else. Take different action depending on value of variable.
If isLeapYear is true, then print "is a".
Otherwise, print "isn't a ".


System.out.print(year + " ");
if (isLeapYear) {
System.out.print("is a");
}
else {
System.out.print("isn't a");
}
System.out.println(" leap
year");
58
Oblivious Sorting
Sort. Read in 3 integers and rearrange them in ascending order.
public class Sort3 {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
read in 3 integers
from command-line
swap b and c
if (b > c) { int t = b; b = c; c = t; }
if (a > b) { int t = a; a = b; b = t; }
if (b > c) { int t = b; b = c; c = t; }
swap a and b
swap b and c
System.out.println(a + " " + b + " " + c);
}
}
% java Sort3 9 8 7
7 8 9
Puzzle 1. Sort 4 integers with 5 compare-exchanges.
% java Sort3 2 1 7
1 2 7
Puzzle 2. Sort 6 integers with 12.
59