CSE 110 Review Session

Download Report

Transcript CSE 110 Review Session

CSE 110 Review Session
Hans Hovanitz, Kate Kincade, and Ian Nall
Quick Intro
• What is a program?
o
List of instructions a computer can follow
• Variable: is a name that refers to a location in memory
o
They store values which can be different types called Data Types
• Variables must be declared and initialized
• Primary data types are:
o
Integer
String
o
Float
Char
o
Double
Boolean
If and If-Else Statements
• The If and If-Else statements use decision logic
• In order to properly use if and if-else statements, relational operators must be
used.
o
== : equal
o
> : one value is greater than another
o
< : one value is less than another
o
!= : not equal
o
compareTo() : method used to compare multiple Strings
• Whenever relational operators are used, a boolean value is returned
Quick Example
if(x==5){ //if the variable x has a value of 5
System.out.print(5); }
else{ //if the above if statement is not true
System.out.print(“Not a 5”);}
Sample Problem
What is the output of this code?
int i = 6;
if(i > 10){
System.out.println(“Big number!”);
}else if(i ==10){
System.out.println(“Almost big.”);}
else
{System.out.println(“Small number!”);}
Small Number!
Loops
• Unlike If-Else statements, loops use iterative logic
o
Meaning, loops are used in order to perform the same operation multiple times
• Every loop requires four components:
o
initialization of a variable local to the loop
o
a stopping condition
o
incrementation or a modification statement
o
The operation or operations to be done within the loop
Quick Example
for(int i = 0; i < 10: i++){
System.out.print(i + “ ,”);
}
What is the output of this loop?
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Sample Problem
What is the output of the following code? Additionally, where is the incrementation
statement, initialization, stopping condition, and operation to be done within the
loop?
int i = 10;
while(i>0){
Initialization
Stopping Condition
System.out.print(i + “, ”);
i = i-2;
}
Output: 10, 8, 6, 4, 2
Operation to be done
within the loop
Incrementation
Statement
Methods - Review
What is a method?
● A method is a sequence of code instructions that are given a
name
● A method exists within a class
● Several methods can exist within a class
● A method takes in 0 to many arguments (inputs)
● A method returns 0 or 1 return values (output)
● Code inside the method uses the arguments
What is a method good for?
● Methods are useful when you need to execute the same set of
instructions many times in your program (not in a loop)
● Methods are useful for breaking up code into smaller, more
manageable logical chunks
Methods - Header/Definition and Example
A method header (also known as a definition) specifies four things:
● The name of the method
● The parameters of the method and their types
● The return type of the method
● Visibility and other modifiers
public static int sum (int num1, int num2)
{
int result = num1 + num2;
return result;
}
Method Practice
How can we create a method that takes an integer as a parameter and returns the
sum of all the numbers before and including that number -- e.g., 5+4+3+2+1 = 15
public static int countDownSum(int num)
{
int total = 0;
int startCountDown = num;
for (int i = 0; i < startCountDown; i++)
{
total = total + num;
num -= 1; //This is the same as num = num -1;
}
}
return total;
Creating a Method - You Try
Create a method header with the following properties:
• Its name is “rateMovie”
• It takes 2 arguments. One argument is a String corresponding to the name of
a movie. The second is an integer value which is a rating of that movie.
• Nothing is returned.
Solution:
public static void rateMovie(String movieName, int rating)
Creating a Method - You Try
Create a method that will calculate the volume of a box and
return the sentence “Volume is large.” if the volume is greater
than or equal to 100.0. If the volume is less than 100.0 your
method should return the sentence “Volume is small.” Your method should also
print the volume of the box to the console.
Don’t worry about the units of the box.
• What parameters does the method require? Hint: There are 3
• What is the return data type?
• Do you need to print out the volume of the box before or after the return
statement?
Creating a Method - Possible Solution
public static void main (String [] args) {
System.out.println(boxSize(5.0, 7.0, 2.0));
}
public static String boxSize(double length, double width, double height) {
double volume = length * width * height;
String result = “”;
System.out.println(volume);
if (volume >= 100) {
result = “Volume is large.”
}
else {
result = “Volume is small.”
}
return result;
}
Output of this program is:
70.0
Volume is small.
Classes and Objects
• Class: Defines the object type
• Object: an instance of a class
• An object has:
o
Variables
o
Methods
• Classes are used to define these for objects of its type
• Meaning, a class is a blueprint for an object of that class!
Brief Example
public Class Rectangle{
public int width, height;
public Rectangle(int height1, int width1){
width= width1;
height = height1}
public int perimeter(){
int perimeter = 2*length + 2*height
return perimeter;
}
}
Make Your Own Class!
Make your own dog class that has:
• A constructor with two arguments: one String which will contain the name of the
dog and an integer which will contain its age
• A method that will determine whether or not the dog is old based on the age (if
age > 5 then the dog is old). This method doesn’t need to return anything.
• Once you are finished making the class, write the code that would create an
object of the dog class.
Possible Solution
public Class Dog{
public String name = “ ”;
public int age = 0;
public Dog(String thisName, int thisAge){
name = thisName;
age = thisAge;}
public void isOld(){
if(age > 5){System.out.println(“This is an old dog”);}
else{ System.out.println(“This dog isn’t old!”);}
}
}
Dog fido = new Dog(“Fido”, 2);
Arrays - Review
An array has these properties:
• Elements - These are the values or objects that make up the array. All of the
elements in an array must be of the same type
• Length - The number of elements that make up the array.
• An array is fixed in length - Once you set the size of an array it cannot be
changed
• The first element of an array is located at index 0
Array Syntax:
<type> [] <variable name> = new <type>[<size>];
Elements unknown: int [] scores = new int[5];
Elements known: int [] scores = {90, 80, 75, 85, 90}
Arrays - Review
int [] scores = new int [5];
What happens if you try this?
scores[1] = 90;
scores [2] = 80;
int exam3 = 85;
scores [3] = exam3;
int exam5 =scores[5]
grades[5] = 100;
//Out of bounds exception!
//Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException
What element is at each index?
0
90
80
85
0
0
1
2
3
4
Array Practice
How can we create an array with 3 elements and ask the user to fill the array with
movie titles? We should then print each element of the array unless the title is “Star
Wars”. If the title is “Star Wars” we should print “Please be awesome”.
Array Practice - Possible Solution
Scanner scan = new Scanner(System.in);
String [] movies = new String[3];
movies[0] = scan.nextLine();
movies[1] = scan.nextLine();
movies[2] = scan.nextLine();
for (int i = 0; i < movies.length; i++
{
if (movies[i].equals(“Star Wars”))
{
System.out.println(“Please be awesome”);
}
else
{
System.out.println(movies[i]);
}
}
Array Practice - You Try
What is the output of this program?
int [] numbers = {1, 2, 3, 4, 5};
int var1 = 2;
int var2 = 4;
if (numbers[4] == variable 2) {
numbers[1] = numbers[2];
}
else {
numbers[2] = var1;
var2 = numbers[3];
}
while (var2 > var1) {
numbers[1] = numbers[1] +2;
var1++
}
numbers[4] = (numbers[3])/2;
for (int i = 1; numbers.length > i; i++) {
System.out.println(numbers[i])
}
index
0 1 2
3 4
numbers = [1], [2], [3], [4], [5]
var1 = 2
var2 = 4
Output:
6
2
4
2
numbers = [1], [2], [2], [4], [5]
var2 = 4
numbers = [1], [4], [2], [4], [5] :
var1 = 3
:
numbers = [1], [6], [2], [4], [2]
numbers = [1], [6], [2], [4], [5]
var1 = 4
ArrayLists
ArrayLists expand and shrink dynamically as needed
Some commonly used methods:
• add
• get
• size
• set
ArrayList Syntax:
ArrayList<type> <name> = new ArrayList<type>();
Arraylist<Integer> scores = new ArrayList<Integer>();
ArrayLists - You Try
What is the output of this program?
Arraylist<Integer> scores = new ArrayList<Integer>();
scores.add(50);
scores.add(75);
System.out.println(scores.size());
int removedScore = scores.remove(1);
scores.add(removedScore + 10);
scores.set(0, 100);
scores.add(2, 85);
for (int i = 0; i <scores.size(); i++)
{
System.out.println(scores.get(i));
}
Output:
2
100
85
85
Recursive Methods
• A recursive method is a method which calls itself
• A couple of items are required for a recursive method:
o
Base case
o
Code that will aid in getting closer to the base case
• Quick example:
public int factorial(int number)
{if(number ==1 || number == 0){
return 1;}
else{return factorial(number-1)*number;}
}
Write your Own Recursive Method!
Write a recursive method that will calculate the sum of all numbers up to a specific
number (meaning, if the number is 5, calculate 5+4+3+2+1). What is the base case?
How can you get closer to the base case given a larger “size n” problem?
Possible Solution
public int addition(int number)
{ if(number == 0){
return 0;}
if(number ==1 |){
return 1;}
else{return addition(number-1)+number;}
}
Questions?
Extra Questions
Loops - Practice
public static void main (String[] args)
{
for (int i = 0; i < 3; i++)
{
for (int j = 3; j > i; j--)
{
System.out.println(j)
}
System.out.println();
}
}
What is the output of this program?
Solution
3
2
1
3
2
3
Methods - Practice
Create a method that determines whether or not a positive integer number is even
or odd. If the number is odd, your method should return -1. If it is even, your
method should return 1. If the number is invalid (not positive), then your method
should return 0.
Solution
public static int isEven(int number)
{
int returnValue = 0;
if (number > 0)
{
if (number % 2 == 0)
{
returnValue = 1;
}
else
{
returnValue = -1;
}
}
return returnValue;
}
Arrays - Practice
Write a program that will find the maximum and minimum value of an array that
contains the values 0.12, 0.81, 0.45, 0.03, 0.80. Then print out the max and min values.
Solution
public static void main(String [] args)
{
double [] values = {0.12, 0.81, 0.45, 0.03, 0.80};
double max = values[0];
double min = values[0];
for (int i = 0; i < values.length; i++)
{
if (values[i] > max)
{
max = values[i];
}
if (values[i] < min)
{
min = values[i]
}
System.out.println(“The maximum value is “ + max);
System.out.println(“The minimum value is “ + min);
}
}
Recursion-Practice
What does this method do? When this method is called, will it return anything?
public int addition(int number){
return addition(number-1)+number;
}
It won’t return anything and it will run forever since there is no stopping
condition!