Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Convert the following C++ code to equivalent Java. Change the arrays/vectors to

ID: 3821562 • Letter: C

Question

Convert the following C++ code to equivalent Java. Change the arrays/vectors to ArrayList's. (Ignore the fact that 0.0 is an inappropriate default value – you can look up 's NAN and isnan() and Java's Float.NaN if you want a better option.)

class Q1

{

private: float * vals;

int numVals;

static const float EPS = .00001;

Generator gen;

public: Q1(int _numVals, float val1, Generator & _gen) : numVals(_numVals), gen(_gen)

{ vals = new float[numVals];

vals[0] = val1;

for (int i = 1; i < numVals; i++) vals[i] = 0.0f; }

float getNth(int n)

{ if (n < 0 || n >= numVals) throw "index out of bounds";

if (-EPS < vals[n] && vals[n] < EPS) vals[n] = gen.calc(getNth(n-1)); return vals[n]; }

};

Explanation / Answer

Hi, Please find my code.

import java.util.ArrayList;

public class Q1 {

   // instance variable

   private ArrayList<Float> vals;

   private int numVals;

   private static final float EPS = .00001f;

   private Generator gen;

   public Q1(int _numVals, float val1, Generator _gen) {

       this.numVals = _numVals;

       gen = _gen;

       vals = new ArrayList<>(numVals);

       vals.set(0, val1);

       for (int i = 1; i < numVals; i++)

           vals.set(i, 0.0f);

   }

   float getNth(int n){

       if (n < 0 || n >= numVals)

           throw new ArrayIndexOutOfBoundsException("index out of bounds");

       if (-EPS < vals.get(n) && vals.get(n) < EPS)

           vals.set(n, gen.calc(getNth(n-1)));

      

       return vals.get(n);

   }

}