CS275 TEST #1

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What's the meaning of a static method? How's activation different from that of an ordinary method?

A static method isn't activated by any one particular object. It's activated by writing a class name, a dot, method name, argument list. For ex.: IntArrayBag.union(b1,b2)

Location distance method is static method. What effect does this have on how the method is used? What effect does this have on how the method is implemented?

A static method isn't activated by one object. Class name is placed in front to activate it. Within implementation of a static method, we can't directly refer to the instance variable.

Supposed that t1 and t2 are throttle variables and that t1 is null but t2 refers to a void throttle. Which of these statements will cause an error? (a)t1=t2 (b)t2=t1 (c)t1.shift(2)

(c) because you can't activate methods when t1=null

What are the primary differences between a bag and a HashSet?

-A bag allows duplicate values in the container. -A HashSet requires unique variables.

Describe public access, private access, package access. What key words are needed to obtain each kind of access for a method?

-public access is obtained with keyword public. Allows access to any program. -private access is obtained with keyword private. Allows access only to methods of the class. -package access is obtained with no keyword. Allows access within the package.

What's the output from this code? int[] a, b; a=new int[10]; a[5]=0; b=a.clone(); a[5]=42; System.out(b[5]);

0

What's the output? Throttle t1; Throttle t2; t1=new Throttle(100); t2=t1; t1.shift(40); t2.shift(2); S.o.pln(t1.getFlow());

0.42

Draw a picture of mybag.data after these statements: IntArrayBag mybag=new IntArrayBag(10); mybag.add(1); mybag.add(2); mybag.addMany(1,3,4); mybag.remove(1);

4 2 1 3 [0] [1] [2] [3] We don't care what appears beyond data[3].

What's the output from this code? int[] a, b; a=new int[10]; a[5]=0; b=a; a[5]=42; System.out(b[5]);

42

What happens if you try to activate a method of the null reference?

A NullPointerException is thrown

In general, how does an iterator become invalid?

By changing its underlying collection.

What's the result when you add 2 double numbers and the answer is larger than the largest possible double number?

Double.POSITIVE_INFINITY

Write statements that declare a seq. and insert number 1-100 into the seq.(in that order).

DoubleArraySeq s; int i; s = new DoubleArraySeq(100); for(i = 1; i <= 100; i++) s.addAfter(i);

Write code that declares 2 locations: 1 at the origin and 1 at the coordinates x=1 and y=1. Print the distance, create 3rd location that's the midpoint.

Location p1=new Location(0,0); Location p2=new Location(1,1); S.o.pln(Location.distance(p1,p2)); Location p3=Location.midpoint(p1,p2);

Suppose I have int b = new int[42]. What are the highest and lowest legal array indexes for b?

Lowest = 0 Highest = 41

Midpoint method, we used (p1.x/2)+(p2.x/2). Can you think of a reason why this expression is better than (p1.x+p2.x)/2?

It could result in a overflow

What are good boundary values to test the removeCurrent method?

It should be tested when the seq.'s size is just 1 and when the seq. is at its full capacity

Which of the ADT's--the bag or seq.--must be implemented by storing the elements in an array?

Neither of the classes must use an array.

How many nodes are in an empty list? What are the values of the head and tail references for an empty list?

No nodes. The head and tail are null.

Supposed "control" is a null reference. What happens if a program tries to activate control.shift?

NullPointException is thrown

What kind of exception will be thrown by these statements? int[] b; b[0]=12;

NullPointerException

Repeat the previous exercise using these two initial statements: int[] p=new int[100]; int[] s=p.clone();

Only p[99] = 75

Use the arraycopy method to copy 10 elements from the front of an array x to the front of n array y.

System.arrayCopy(x, 0, y, 0, 10);

Suppose x and y are arrays w/ 100 elements each. Use arraycopy to copy x[10]...x[25] to y[33]...y[48].

System.arrayCopy(x, 10, y, 33, 16);

Would the, add method, work correctly if we used, ensureCapacity(manyItems+1) without the *2?

The capacity would always increase by one, but increasing 1 by 1 will be inefficient

The, add method, uses ensureCapacity(manyItems*2+1). What would go wrong if we forgot the +1?

The capacity wouldn't increase.

Supposed a method has a Location param. called x, and the body of the method activates x.rotate90(). When the method is activated, what happens to the argument that corresponds to x?

The object that the argument refers to has been rotated 90 degrees.

Class Thermometer. No argument constructor, that sets class temp to 0C. 2 modification methods to change temp by a specific amount. 2 accessor methods to get current temp. Class keeps track of 1 temp, but can access in Celsius or F. Write code to class, add 10C, print F temp.

Thermometer t=new Thermometer(); t.addCelsiui(10); S.o.pln(t.getFahrenheit());

Describe the extra work that must be done at the end of the clone method. Draw pictures to show what goes wrong if this step is omitted.

You need an additional statement to make a separate copy of the data array for the clone to use.

The bag in the preceding question has a capacity of 10. What happens if you try to add more than 10 elements to the bag?

When the 11th element is added, the add method will increase the capacity to 21.

What's the purpose of the java constant Double.NaN?

When there isn't a valid number to store in a double variable.

A method declares a Throttle variable called "control", but there isn't yet a throttle. What value should be assigned to "control"?

control should be assigned to null

Suppose g is a seq. w/ 10 elements, you activate g.start() and then activate g.advance() 3x. What value is then in g.currentIndex?

g.currentIndex will be 3

Write the import statement that must be present to use the package from previous questions.

import com.knafn.statistics.*;

Supposed you need 1 class(called Averager) from the package of the previous questions. Rewrite the import statement to import only one package.

import com.knafn.statistics.Averager;

Write code that follows these steps:Declare an int array variable called b; allocate a new array of 1000 integers for b to refer to; place the numbers 1-1000 in the array.

int i; int[] b; b = new int[1000]; for(i = 1; i <= 1000; i++) b[i-1] = i;

Design and implement a class Clock

look on page 677

Implement a clone method for the Throttle class.

look on page 69

consider the following statements: int[] p = new int[100] int[] s = p Which of the following statements will change the last value of p to 75? p[99]=75; p[100]=75; s[99]=75; s[100]=75;

p[99] = 75 or s[99] = 75

Write package declaration that will appear at the top of every java file for the package of previous 2 questions.

package com.knafn.statistics;

Write a new throttle constructor with no arguments. The constructor sets the top position to 1 and sets the current position to of.

public Throttle(){ top=1; position=0; }

Write another throttle constructor with 2 arguments. The total number of positions for the throttle, and its initial position.

public Throttle(int size, int initial){ if(size<=0) throw new IllegalArgumentException ("Size<=0:"+size); if(initial<0) throw new IllegalArgumentException ("Initial<=0:"+initial); if(initial>size) throw new IllegalArgumentException ("Initial too big:"+initial); top=size; position=initial; }

Implements and "equals" method for the Throttle class from 2.1.

public boolean equals(Object obj){ if(obj instanceof Throttle){ Throttle candidate=(Throttle) obj; return (candidate.top==top) && (candidate.position==position); } else return false; }

Add a new throttle method that will return true when the current flow is more the half of the max flow. It should activate the getFlow method.

public boolean isAboveHalf(){ return(getFloe()>0.5); }

Use the new form of the for-loop to write a method that counts how many times a certain target appears in an integer array.

public static int count(int[] a, int target) { int answer = 0; for(int item : a){ if(item == target) answer++; } return answer; }

Write a method that copies n elements from the front of one integer array to the front of another. The 2 arrays and the number n are all arguments to the method. Include the precondition/postcondition contract as part of your implementation.

public void copyFront(int[] a, int[] b, int n) { int i; for(i = 0; i < n; i++) b[i] = a[i]; }

Suppose x is a double number. Write statements that insert x into the seq. from previous exercise. The insertion should occur so that all the numbers of the seq. remain in order smallest to largest.

s.start(); while(s.current() && s.current() < x) s.advance(); if(s.isCurrent()) s.addBefore(x); else s.addAfter(x);

Write demo. program that asks user for list of family members ages then prints the list in the same order it was given.

similar to Figure 3.2 on pg. 123

Write seq.'s addBefore method.

void addBefore(double element) { int i; if(manyItems == data.length) { ensureCapacity(manyItems*2 + 1); } if(! isCurrent()) currentIndex = 0; for(i=manyItems; i>currentIndex; i--) data[i] = data[i-1]; data[currentIndex] = element; manyItems++; }

Write new method to remove a specified element from a seq.. The method has 1 param.(the element to remove).

void remove(int target);

Suppose a seq. has 24 elements, there's no current element. According to the invariant of the ADT, what's currentIndex?

24

Describe 2 uses for null reference in realm of linked lists.

1) Null reference is used for the link part of the final node of a linked list 2) Used for the head and tail references of a list that doesn't yet have any nodes

Write the invariant of the bag ADT.

1) The number of elements in the bag is stored in the instance variable manyItems 2) For an empty bag, we don't care what's stored in any of data.

For seq. of numbers, suppose you insert 1, then 2, then 3, up to n. What's the big-O time analysis for the combined time of inserting all n numbers with addAfter? How does the analysis change if you insert n first, then n-1, down to 1--always using addBefore instead of addAfter?

1) The total time to add is O(n) with addAfter 2) The total time to add is O(n^2) with addBefore

What elements will be in the sequence s after these statements? DoubleArraySeq s=new DoubleArraySeq(); s.addAfter(1); s.addAfter(2); s.start(); s.addAfter(3);

1, 3, 2 (in that order). The current element is the 3.

Which kind of method often has a void return type? Why?

Accessor methods aren't usually void type as Modification methods usually are void.

Describe the difference between a modification method and an accessor method.

An accessor method doesn't make changes to the objects instance variables

Why don't we list the bag invariant as part of the explicit precondition and postcondition of the bag methods?

Because the programmer who uses the bag class doesn't need to know this info.

Examine the techniques for adding and removing a node at the head. Why are these techniques implemented as static methods rather than ordinary IntNode methods?

Because you can't implement ordinary methods of the IntNode class.

Suppose we implement addAll as shown in fig. 3.8 on pg142. What goes wrong with b.addAll(b)?

The loop never ends.

Write some code that could appear in a main program. The code should declare head and tail references for a linked list of integers and then create a list of nodes w/ the data being integers 1-100(in that order). After each of the nodes is added, 'head' and 'tail' should still be valid references to the head and tail nodes of the current list.

IntNode head; IntNode tail; int i; head = new IntNode(1, null); tail = head; for(i = 2; i <= 100; i++) { tail.addNodeAfter(i); tail = tail.getLink(); }

When should a program throw a RuntimeException?

RuntimeException indicates a programming error

Supposed a method has a int param. called x, and the body of the method changes x to 0. When the method is activated, what happens to the argument that corresponds to x?

The argument remains unchanged

Suppose an array is passed as a parameter to a method, and the method changes the first component of the array to 42. What effect does this have on the actual argument back in the calling program?

The array referred to by the parameter in the method is the same as the array referred to by the actual argument. The actual argument will have the first component changed to 42.

Which bag methods do not have the bag invariant as part of their implicit precondition?

The constructors

Suppose a program builds and manipulates a linked list. What 2 special nodes would the program typically keep track of?

The head node and tail node

Write a java code that creates a new throttle with six positions, shifts halfway up, prints current flow.

Throttle exercise=new Throttle(6); exercise.shift(3); S.o.pln(exercise.getFlow());

Write code that will make t1 and t2 refer to 2 different throttles with 100 positions each. Both shifted to position 42. At the end, is (t1==t2) true or false?

Throttle t1; Throttle t2; t1=new Throttle(100); t2=new Throttle(100); t1.shift(42); t2.shift(42)

At the end of the codes computation, is (t1==t2) true or false?

True, because there's both variables refer to the same throttle.

Describe the directory structure that must be set up for the files of the package in the preceding question.

Under classes directory, create subdirectory com. Under com create subdirectory statistics. Package is placed in statistics subdirectory.

Describe the 3 kinds of class members we have used. In this section, which kinds of members were public and which were private?

We use private instance variables, public constructors, public methods

What's your guess for the running time required for the 3 arithmetic operators of add, sub, mult?

add and sub are O(n), n=greatest degree mult. is O(m x n), m,n=degrees

Which of the seq. methods have implementations that could be identical to the bag methods?

addAll, getCapacity, size, trimToSize

Write java expression that will indicate how many elements are in the array b(from previous exercise).

b.length

Suppose you implement the polynomial class using an array called, coef. What values will be stored in coef for the polynomial 0.3x^3+0.5x^2-0.9x^1+1.0?

coef[0]=1.0; coef[1]=-0.9; coef[2]=0.5; coef[3]=0.3; the rest of coef is all zero

Supposed you're writing a package for a company that has internet domain "knafn.com". The classes in package that perform various statistical functions. Select a good name for the package.

com.knafn.statistics

What are the instance variables for our sequence implementation?

data, manyItems, currentIndex

Use the expression, --manyItems, to rewrite the last two statements of remove as a single statement.

data[index] = data[--manyItems];

Suppose 'head' is a head reference for a linked list on integers. Write a few lines of code that will remove the second node of the list.

if(head != null) { if(head.getLink() == null) head = null; else head.removeNodeAfter(); }

Suppose 'head' is a head reference for a linked list on integers. Write a few lines of code that will add a new node w/ 42 as the second element of the list.

if(head == null) head = new IntNode(42, null) else head.removeNodeAfter(42);

Write a static method that has 1 param.: a non-empty HashSet of strings. The return value is the average of the strings' lengths.

import java.util.HashSet and java.util.Iterator public static double ave_len(HashSet<String> c) { Iterator<String> it; double total = 0; if (c.size() == 0) throw new IllegalArgumentException ("Empty HashSet!"); it = c.iterator(); while (it.hasNext()) { total += it.next().length(); } return total/c.size(); }

Redo the preceding exercise with only five elements instead of 1000. Your solution should be just a single Java statement.

int[] b = new int[] {1,2,3,4,5};

What import statement is needed to use the java.lang package?

java automatically imports java.lang;no explicit import statement is needed.

Supposed you implement a class, but you don't write a constructor. What kind of constructor does java usually provide automatically?

java provides a no-argument constructor that sets each instance variable to its initialization value or to its default value

Write another node declaration, the data in each node should include both a double number and an int.

public class DINode { double d_data; int i_data; DINode link;

Write the start of the class declaration for a node in a linked list. The data in each node is a double number.

public class DoubleNode { double data; DoubleNode link; . . . }

Write new bag method that removes all copies of a specified target from a bag. The return value should be the number of copies of the target that were removed from the bag.

public int removeAll(int target) { int i; int count = 0; i = 0; while(i < manyItems) { if(data[i] == target) { manyItems--; data[i] = data[manyItems]; count++; } else i++; } return count; }

Write variable-arity version of, remove method. The return value is total number of elements removed from the bag.

public int removeMany(int... targets) { int count = 0; for(int target : targets) count += remove(target); return count; }

Write static bag method called, intersection, that creates a new bag from 2 other bags b1 and b2. The number of copies of an int x in the new bag will always be min. of b1.countOccurrences(x) and b2.countOccurrences(x)

public static IntArrayBag intersection(IntArrayBag b1,IntArrayBag b2) { int i, j; int count; int it; IntArrayBag a; answer = new IntArrayBag; for(i = 0; i < b1.manyItems; i++) { it = b1.data[i]; if(a.countOccurrences(it)==0) { count = Math.min(b1.countOccurrences(it), b2.countOccurrences(it)); for(j = 0; j < count; j++) { a.add(it); } } } return a; }

Write method called, zero_some, with 1 param. x that's an array of double numbers. The method changes x[0], x[2], x[4], ..., all to 0. If you activate zero_some(a) for an actual array a of length 6, which components of a will be changed to 0?

public void zero_some(int[] x) { int i; for(i = 0; i < x.length; i += 2) x[i] = 0; } After some_zero(a), these elements of a will be 0: a[0], a[2], a[4].

What does the automatic "equals" method do?

returns true when 2 objects are exact same


Ensembles d'études connexes

Which of the following is the correct sequence of events in cellular respiration

View Set

150 preguntas y respuestas más comunes en inglés

View Set

Computer and Information Security Handbook

View Set

Antonio López de Santa Anna (1821-1855)

View Set