I am a beginner when it comes to java and am having some issues(been sitting in front of this all day). I have searched far and wide for a solution, yet to no avail. My professor has asked me to fill out the blank methods, and I am especially having trouble with the toString method(although I am not feeling to good about the rest either), any help would be appreciated.
import java.util.Random;
public class SmartArray {
// declare an array of ints
int[] list;
Random r = new Random();
int pos = 0;
/**
* Creates and initializes an array of size n. It does not initialize the
* contents of the array.
*/
public SmartArray(int n) {
list = new int[n];
}
/**
*
* Initializes the contents of the array with random
*
* non-negative* numbers.
*
*/
public void initRandom() {
int i = 0;
int hold = 0;
while (i < list.length) {
hold = r.nextInt();
if (hold % 2 == 0) {
list[i] = hold;
i++;
} else {
hold = hold + 1;
list[i] = hold;
i++;
}
}
}
/**
*
* Allows client code to add an element to the array
*
* at the given position. Throws an ArrayIndexOutOfBounds
*
* exception with a message if the
*
* position is out of bounds.
*
*/
public void insert(int value, int pos) {
if (list.length > pos) {
list[pos] = value;
} else {
throw new ArrayIndexOutOfBoundsException("The position of your value is greater than the array");
}
}
/**
*
* Returns the position of target if target is
*
* one of the values in the array, otherwise -1.
*
* Implemented with a loop.
*
*/
public int find(int target) {
int position = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == target) {
position = i;
} else {
position = -1;
}
}
return position;
}
/**
*
* Same as the find method, except that it's implemented
*
* using recursion. (Hint: use a helper method.)
*
*/
public int recursiveFind(int pos, int target) {
if (pos >= list.length) {
return -1;
} else if (list[pos] == target) {
return pos;
} else {
return recursiveFind(pos + 1, target);
}
}
/**
*
* Returns the elements of the array, separated by
*
* spaces, with a newline after every 10 elements,
*
* so they can be easily displayed.
*
*/
public String toString() {
String listString = "";
int pos = 0;
for (int i = 0; i < list.length; i++) {
//list[i].toString();
listString = listString + (String) list[i] + " ";
pos++;
if (pos > 9) {
list = list + "\n";
pos = 0;
}
return listString;
}
}
}