I have need for the following.
Vector v = new Vector();
public void addToVector(int[] myArray, int index) {
v.addElementAt(myArray, index);
}
But, I only want to add the array at the specified index if another array
does not already occupy this space.
The reason for this is to store answers given in a quiz. The answers given
are stored in the array, and the array is added to a session scoped vector.
Basically, I only want the user to be able to answer once during the
session, not being able to correct the answers and resubmit.
So, I was trying something like assigning the element to a temp variable
like so...
int[] tempArray = (int[]) v.elementAt(index);
then, test for a size of greater than zero, but it does not work. If there
is no element at index, then elementAt throws a JasperException.
Any ideas?
Anthony Borla - 20 Feb 2005 05:54 GMT
> I have need for the following.
>
[quoted text clipped - 20 lines]
>
> Any ideas?
Several approaches are possible. Here is a very simple one based on your
code which assumes that there is a fixed number of questions - the Vector is
built to have an element corresponding to each question, and is then filled
with null values [each indicating an unanswered question].
As you add responses for questions a check is made to see if:
* The question number is valid
* The validated question has been answered or not
This should provide a reasonable starting point for your own solution.
I hope this helps.
Anthony Borla
// ------------------------------
// Test Code
...
TestQuestions t = new TestQuestions(3);
t.addResponses(new int[]{1,2,3}, 1);
t.addResponses(new int[]{1,2,3}, 5);
t.addResponses(new int[]{1,2,3}, 1);
...
// Code Proper
class TestQuestions
{
private Vector q;
public TestQuestions(int questions)
{
q = new Vector(questions);
for (int i = 0; i < questions; i++)
q.add(null);
}
public void addResponses(int[] responses, int questionNumber)
{
// Test for validity of questionNumber
if (q.size() <= questionNumber)
{
// Not a valid question number ...
System.err.println("Invalid question number ...");
}
// Check for existing responses for question
else if (q.elementAt(questionNumber) == null)
{
// Currently unoccupied, so add responses
q.add(questionNumber, responses);
}
else
{
// Question already answered
System.err.println("Question already answered ...");
}
}
}