2

i have done this so far, but having difficulty with part b. It is a mock exam paper and not sure on the rest of part b.

Q) Sum up the elements of a sequence given by s.valAtIndex(i). s is of type Seq. Seq is an interface that has a method valAtIndex (integer parameter and double result).

(a) write the interface Seq.

(b) write a class Geometric, implementing Seq. so that each instance s represents a geometric series as follows s.valAtIndex(0), s.valAtIndex(0)... such that the ith element s.valAtIndex(i) is equal to the ith power of the base b i.e. b^i. (recall that b^0=1)

(a)

public interface Seq{

public double valAtIndex(int i);
}

(b)

public Geometric implements Seq{

Seq s;
private double b;

public Geometric(double a){

s = new Geometric(a);
this.b=a;
}

@Override
public double valAtIndex(int i){

return 0;//not sure how to do this method

}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
nsc010
  • 395
  • 3
  • 5
  • 12
  • You don't need to create an instance of `Geometric` inside your constructor. That's what the constructor is doing. – Dancrumb Aug 09 '12 at 21:07
  • 1
    @Dancrumb That would be an infinite recursive loop, causing a stackoverflow exception. Also, it would be nice if this were labeled better... a->r, i->n. valAtIndex is pretty easy, just use the formula: u0*r^(n-1). – Ryan Amos Aug 09 '12 at 21:08

2 Answers2

7

You mean something like:

@Override
public double valAtIndex(int i) {
    return Math.pow(b, i);
}

?

EDIT: Also, as mentioned in other answers, remove Seq s; and the line regarding it in the constructor. What you should have at the end is:

public class Geometric implements Seq {
    private double b;

    public Geometric(double a) {
        this.b=a;
    }

    @Override
    public double valAtIndex(int i){
        return Math.pow(b, i);
    }
}
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
  • Regarding edits: I was a little confused for a bit regarding `@Override` tags for interface methods, http://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why clears things up a bit. – Dennis Meng Aug 09 '12 at 21:21
0

First,

@Override
public double valAtIndex(int i) {
    return Math.pow(b, i);
}

This would return b to the power of i.

However, your code would result in a stack overflow exception. You call a constructor for geometric inside the constructor. resulting in continious calling to the constructor and an exception.

You need to change your constructor to

public Geometric(double a) {
    this.b = a;
}

Also, you need to declare it as class Geometric instead of public Geometric

La bla bla
  • 8,558
  • 13
  • 60
  • 109