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

}
2
  • You don't need to create an instance of Geometric inside your constructor. That's what the constructor is doing. Commented Aug 9, 2012 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). Commented Aug 9, 2012 at 21:08

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Regarding edits: I was a little confused for a bit regarding @Override tags for interface methods, stackoverflow.com/questions/94361/… clears things up a bit.
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

1 Comment

Sorry I forgot to add the class, was typing what I had wrote

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.