2013 - Zoo - Yale University

Download Report

Transcript 2013 - Zoo - Yale University

CS 112 Introduction to
Programming
Pre-Midterm Exam Review Session
Computer Science Department
Yale University
March 27, 2013
Admin
 Assignments
Assignments 1-5: Returned (via Assignments tab)
 Assignment 6: Due Mar. 26 (yesterday), 11:55 PM
 Assignment 7: Will Be Posted Shortly

 Midterm – Friday, Mar. 29 during class
 Office Hours – Every Day this Week
 Check the CS112 website for the schedule
 Send us feedback!
2
Midterm Structure
 Content

List of topics covered available on the class website
 Question Types
 Writing Methods or Code Snippets
 Making Corrections to Code
 Analyzing “Black Box” Algorithms
 Discussing Code Implications, Trade-offs, etc.
 Study
 Lectures thru Mar. 25
 Homework thru Assignment 6
 Readings Listed in the Class Schedule (thru Mar. 25)
3
Review Session Overview
 Core Content Areas







Basic Java Architecture
Primitive Data Types
Variables
Flow Control
Program Analysis Using Assertions
Methods
Standard Java Classes
 Sample Questions
4
Basic Java Architecture
 Java is architecture-neutral – compile once,
and your code works anywhere via the “Java
Runtime Environment”
 Using Java:
 runs a Java .class file via the Java runtime
 javac  compiles Java source code (.java files) into
Java “bytecode” (.class files)
 jar  enables compression of multiple files (e.g.,
.java, .class, etc) into a single file
 java
5
Primitive Data Types
Data Type
Description
Examples
int
Numeric: Whole numbers
int x = 123;
double, float Numeric: Includes Decimal
double x = 123.001;
boolean
True/False (yes/no, on/off)
boolean x = true;
char
Single letter/number character
char x = ‘a’;
String
Multiple letter/number characters
String x = “Hello
world”;
 Traditional order of operations applies
 Remember:
Numeric operations require numeric data types
 Typecasting numeric values is a “safe” approach
 Integer math is non-conventional! (e.g., rounding)

6
Primitive Data Types
Operator
Description
Examples
=
Assignment operator
int x = 123;
==, !=
Tests for equality/inequality
if (x == y)
<=, >=
Less than/greater than
comparators
if (a >= b)
+, -, *, /, %
Addition, subtraction, division,
multiplication, and modulus
int x = 1701 – 30;
+=, -=, *=,
/=, %=
In-line arithmetic/assignment
operators
x += 2;
!
The “not” operator – reverses the
true/false result of an expression
If (!(a == b))
||
Boolean “or” operator
if (a == b || b == c)
&&
Boolean “and” operator
if (a == b && b == c)
7
Variables
 Distinguish local from global variables
public class Hello{
public static String name = “World”; // Global Variable
public static void main(String args[]){
int numTimes = 5; // Local Variable
for (int i = 0; i < numTimes; i++){
System.out.println(“Hello “ + name);
}
}
}
 Use the final keyword for constants!
public static final double PI = 3.14159;
8
Flow Control
Conditional Statements
Loops
if/else if/else
for
switch
while
 All control statements rely on evaluation of
boolean expressions

Determines whether to enter/continue or skipover/exit
 Interchangeability of if/else if/else with
switch, and for with while

Recognize appropriateness of each
9
Flow Control
for (initialization; test; update) {
header
statement;
statement;
...
body
statement;
}
======================================
initialization;
while (test) {
header
for is more appropriate
statement;
when number of
statement;
iterations is known in
...
advance! Otherwise, use
body
statement;
while.
update;
}
10
Flow Control
 Several different loop designs
 Continuous – iterates ad infinitum
 Early Exit – use of the break keyword causes the
loop to “stop early”
 Sentinels – a certain condition is tested on each
iteration and when it is no longer true, the loop exits
(most common)
11
Flow Control
Optional
Optional
if (test) {
statement;
}
else if (test) {
statement;
}
else {
statement;
}
switch (variable) {
case value:
statement;
break;
case value:
Optional
statement;
break;
default:
Optional
statement;
break;
}
 A switch statement is only capable of testing
for equality! (i.e., cannot use other comparison
operations)
12
Program Analysis Using Assertions
 Recognize that testing for a particular
condition in one place ensures that a condition
is true elsewhere
int studentGradeLevel = 9;
if (studentGradeLevel >= 9) {
// Student is grade 9 or higher
...
statement;
// Student is still grade 9 or higher
}
13
Methods
 Definition Format
public static <return-type> <name> (<type> <name>, …) {
<statement>(s);
}
 Calling and Passing Parameters
 rand.nextInt();  no parameters
 rand.nextInt(50);  50 is the parameter
 Because nextInt() is overloaded (i.e., has more than one
definition), both calls work!
 Overloading methods
 Allows multiple methods to share the same name
 Overloaded methods must differ in terms of parameter data
types and/or order
 Variables declared inside methods are local
14
Standard Java Classes
Data
Type
Relevant Methods
Examples
String
length()
Returns length (number of characters) in the String
charAt(int x)
Returns the character in the String at position x
substring(int
startPos, int endPos)
Returns a String containing the characters in the
string from startPos to endPos, inclusive
round(double x)
Returns the integer-rounded value of x
max(int a, int b) /
min (int a, int b)
Returns the larger/smaller of a or b
sqrt(double x)
Returns the square root value of x
Math
Scanner next(), nextInt(),
nextDouble()
Random
Reads next String/int/double from Scanner
hasNext(),
hasNextInt(),
hasNextDouble()
Determines whether there is another
String/int/double to be read from the Scanner
nextInt(int x)
Returns a randomly-generated integer between 0
(inclusive) and x (exclusive)
15
Standard Java Classes
 Other common methods:
System.out.print();
 System.out.println();
 System.out.printf();
 Review printf placeholders

 DrawingPanel and Graphics
16
Standard Java Classes
Method name
Description
g.setColor(Color);
set Graphics to paint any following
shapes in the given color
g.drawLine(x1, y1, x2, y2);
line between points (x1, y1), (x2, y2)
g.drawOval(x, y, width, height);
outline largest oval that fits in a box of
size width * height with top-left at (x, y)
g.drawRect(x, y, width, height);
outline of rectangle of size
width * height with top-left at (x, y)
g.drawString(text, x, y);
text with bottom-left at (x, y)
g.fillOval(x, y, width, height);
fill largest oval that fits in a box of size
width * height with top-left at (x, y)
g.fillRect(x, y, width, height);
fill rectangle of size width * height
with top-left at (x, y)
http://download.oracle.com/javase/6/docs/api/java/awt/Graphics.html
17
Sample Questions
 Identify the syntax and logic problems in the
below code, as well as stylistic issues:
class Hello{ static
public void main(String args[]){
int x = 0;
Add quotes
while (x < 5){
System.out.println(Hello world!);
Use a
x += 1;
x++ is shorter
for
loop
}
instead
public
return true;
}
Method is void, thus
should not have a
return value
}
18
Sample Questions
 What does the below method do?
public static void doSomething(){
for (int i = 0; i < 8; i++){
for (int j = 0; j < i; j++){
System.out.print(“+”);
}
for (int j = 0; j < 8 – i; j++){
System.out.print(“*”);
}
System.out.println(“”);
}
}
Prints:
********
+*******
++******
+++*****
++++****
+++++***
++++++**
+++++++*
Note that this line is not completely filled by plus
signs – be cognizant of off-by-one issues with loops!
19
Questions?
20
Thank You!
21