CS 61B Introduction to Java Spring 2021 Discussion 2: January 25th, 2021
1 Our First Java Program
Below is our first Java program of the semester. Next to each line, write out what you think the code will do when run. If you think the line will result in an error, correct it, and proceed through the code as if it is running your corrected version. This exercise is adapted from Head First Java.
1 size = 27;
2 name = “Fido”;
3 Dog myDog = new Dog(name, size);
4 Dog yourDog = new Dog(“Scruffy”, 1000);
5 Dog[] dogList = new Dog[3];
6 dogList[0] = myDog;
7 dogList[1] = yourDog;
8 doglist[2] = 5;
9 dogList[3] = new Dog(“Cutie”, 8)
10 int x;
11 x=size-5;
12 if(x<15){
13 myDog.bark(8);
14 }
10 11 12 13
2 Introduction to Java 2 Mystery
This is a function (a.k.a. method). It takes an array of integers and an integer as arguments, and returns an integer.
public static int mystery(int[] inputArray, int k) { int x = inputArray[k];
int answer = k;
int index = k + 1;
while (index < inputArray.length) { if (inputArray[index] < x) {
x = inputArray[index];
answer = index;
index = index + 1;
}
return answer; }
(a) Describe what mystery returns if inputArray = [3, 0, 4, 6, 3] and k = 2. (b) Can you explain in plain English what mystery does?
Extra: This is another function. It takes an array of integers and returns nothing.
1
2
3
4
5
6
7
8 9}
public static void mystery2(int[] inputArray) { int index = 0;
1
2
3
4
5
6
7
8 9}
while (index < inputArray.length) {
int targetIndex = mystery(inputArray, index); int temp = inputArray[targetIndex]; inputArray[targetIndex] = inputArray[index]; inputArray[index] = temp;
index = index + 1;
10 }
Describe what mystery2 does if inputArray = [3, 0, 4, 6, 3].
3 Writing Your First Program
Implement fib which takes in an integer n and returns the nth Fibonacci number. You may not need to use all the lines.
The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, . . .. The first two numbers in the sequence are 0 and 1, and every number thereafter it is the sum of the two numbers in the sequence before it.
public static int fib(int n) {
}
Extra: Implement a more efficient version of fib in 5 lines or fewer. Here, efficiency might mean making less recursive calls or doing less overall computation. You don¡¯t have to make use of the parameter k in your solution.
public static int fib2(int n, int k, int f0, int f1) {
}
Introduction to Java 3