|
I am having a bit of trouble with a do while loop. I either can't get it to stop, or it doesn't do exactly as I need it to.
I need to search an array nums and would like to output each number it reaches into a vector. I want it to stop once it has reached the searchValue number and also added this to the vector.
At the moment it is not stopping. I have got it in the past to stop but then it was writing ALL the numbers to the vector. this is why I am now trying to use a do while.
For example the array might be [10,9,24,23,19] and the searchValue is 23. I would want to add only 10,9,24,23 to the vector.
Does that make sense?
Hope someone can help with this.
public void correctSearchPath(int searchValue){
if (outCome == 0) { // node is IN
System.out.println("correctSearchPath node is in tree");
for (i = 0; i < amount; i++){
do {
optimalSearch.add(new Integer(nums ));
System.out.println("searchValue is " + searchValue);
}
while (i != searchValue);
}
System.out.println("optimalsearchpath is: " + optimalSearch);
}
if (outCome == 1){ // node NOT in tree
for (i = 0; i < amount; i++){
System.out.println("correctSearchPath node is NOT in tree");
}
}
System.out.println("outcome of flipCoin is " + outCome);} // method to drawWhole tree
|
|
hope someone can help me with this
|
|
|
The problem is you have nested loops, your while loop is nested inside the for loop, instead of the while loop you could just test the condition with an if statement inside of your for loop. It also seems like your code is doing a lot of unnecessary work but since I don't know exactly what it's supposed to do it's difficult to tell.
for (i = 0; i < amount; i++){
if (i != searchValue)
{
optimalSearch.add(new Integer(nums ));
System.out.println("searchValue is " + searchValue);
}
}
of if you want to use the while loop
i = 0;
do {
optimalSearch.add(new Integer(nums ));
System.out.println("searchValue is " + searchValue);
i++;
}
while (i != searchValue && i < amount);
}
semper fi...
|
|
|
Hi
Thanks for that. I will take another look at my code. I notice you out the so will also try that as I am now getting a arrayexception error on that line when I try and add nums to the vector.
Will let you know if I still have problems. Thanks again!
|
|
|
well you didn't declare nums anywhere in the sample you posted but I would assume that is the array. If it is you probably actually want to access the array using an index like
nums
Just a thought.
semper fi...
|
|
|
|
|
|
|
|