C# Array out of bounds - arrays

I have created for loop but it only executes once instead of multiple times. At first it takes value but after increment ment it doesnot executes but catch an exception of array out of bounds and indexoutofexception.
Why this for loop is not repeating, I can't seem to find its solution.
This is my code
private void CheckForVariable()
{
//to split parameter by , then stored in array
parameter = inputcommand[1].Split(",".ToCharArray());
for (int i = 0; i < parameter.Length ; i++)
{
try
{
//checks if the parameter is an int
int test = Convert.ToInt32(parameter[i]);
//Console.WriteLine(parameter[i]);
}
catch
{
Boolean foundVariable = false;
if (foundVariable == false)
{
foreach (KeyValuePair<string, int> variable in VariableDictionary)
{
if (variable.Key.Equals(parameter[i]))
{
parameter[i] = variable.Value.ToString();
}
}
}
}
}
}
I tried to do exception handling using try catch, it doesnot seems to work. It is only taking single value instead of multiple times. I want to pass repeated value until it executes as expected.

Related

Bool function to check if a word is in an array C++

I'm working on some code check if word is in ignoreWords array. The function keeps returning true for the first value and then false for the rest of the elements even if some of the words are in the ignoreWords array. I'm not sure what I'm doing wrong, I'd appreciate any help or advice.
bool isIgnoreWord(string word, string ignoreWords[])
{
int length;
string copy[length];
for(int i=0; i < length; i++){
copy[length] = ignoreWords[i]; //to find out length of ignoreWords
//cout << copy[length] << endl;
if(copy[length] == word)
return true;
else
return false;
}
//function returns whether word is in the ignoreWords array
}
edit: fixed it. I made it so much more complicated than it really is. This is the code that works:
bool isIgnoreWord(string word, string ignoreWords[])
{
for(int i=0; i < 50; i++){
if(ignoreWords[i] == word){
return true;
}
}
return false;
//function returns whether word is in the ignoreWords array
}
That would be because your if-else statement in the for loop returns in both conditions.
Imagine you're the computer, and you start the for loop:
if (copy[length] == word) {
return true;
}
else {
return false;
}
So you get to the first element in the array, and let's say it doesn't match the word you're checking against. This if-else statement says to return false if it's not, and immediately stops the function because a return statement was found.
What you probably want is for your program to only return false if it exits the for-loop without finding any matches, e.g.
for (...) {
if (matches) return true;
}
return false;
Another thing to note is that you're not initializing length before using it in a statement, and initializing a variable-length array like that isn't supported on all compilers.

how do i exit a for loop in an if else statement? groovy - java

My code worked fine until I added the else block.
String getInputSearch = JOptionPane.showInputDialog("city")
for(int i=0; i < listArray.length; i++) {
if(getInputSearch == loadData()[i][0]) {
for(int j=0; j< loadData()[i].length; j++) {
println(loadData()[i][j])
}
println("")
}
else {
println( getInputSearch+ "not a valid city");
}
}
If I add a break within the else block, the loop only works once and if I don't it keeps printing "not a valid city," even if the city is valid until it reaches the the right index in the array. (data is read from a text file btw)
help would be appreciated.
The problem is there's a mismatch between what you're trying to achieve and your approach. You're trying to determine whether the city is valid or not, and if so, print out some data. However, what you're doing instead is checking if a particular row has a valid city, which leads to your if statement being executed for every iteration; hence the multiple "not a valid city" results. Your if statement is just too early.
Try something like this:
/* Grabs all the rows in loadData() with a matching city.
* Which means that if the list is empty, then the city is invalid.
*/
def cityData = loadData().findAll { it[0] == getInputSearch }
if(cityData) {
cityData.each { row ->
row[1].each { column ->
println column
}
println()
}
} else {
println "${getInputSearch} not a valid city"
}
And if you're feeling fancy, there's a more stream/pipe like approach:
loadData()
.findAll { it[0] == getInputSearch }
.with {
/* asBoolean() tries to coerce the List into a boolean.
* An empty list is False, while a non-empty list is True
*/
if(!delegate.asBoolean()) println "${getInputSearch} not a valid city"
delegate // Return the list itself so that if it's not empty the process will continue.
}.each { row ->
row[1].each { column ->
println column
}
println()
}

getting out of a loop in C

I am trying to get out of a while loop using C, but using breaks, returns or changing the while condition are not working.
Basically, I want to know why in the last else if, when I state back = true my code keeps entering the for.
I would expect an output like: enter1, enter1, enter1, enter1, enter2.
Instead, the output is something like enter1, enter1, enter1, enter2, enter2, enter2, enter1, enter1, enter1....
This is my code work:
void SolveMap8(Core* core_building, Building* new, Stack* solve, bool goingBack){
Core* coreBuilding = core_building;
Building* first = new -> linked[0];
Building* next = NULL;
bool back = goingBack;
while (back == false) {
for (int i = 0; i < (first -> zone -> building_count); i++) {
if (first -> zone -> buildings[i] != NULL) {
if (first != first -> zone -> buildings[i]) {
next = first -> zone -> buildings[i];
if(next -> color == coreBuilding -> buildings[0] -> color && !city_client_is_taken(next)) {
puts("enter0");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
break;
}
else if(!city_client_is_taken(next)) {
if (city_client_is_blank(next)) {
if (!(next -> cored)) {
puts("enter1");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
SolveMap8(coreBuilding, next, solve, false);
}
}
}
else if (city_client_is_taken(next)) {
if (i == first -> zone -> building_count - 1) {
puts("enter2");
back = true;
}
}
}
}
}
}
}
Update Sorry, missed the recursion. In that case your problem has nothing to do with a missing break statement, but that you are trying to escape from a for loop at a different scope than you are currently in. You will need special logic to handle a global "done" condition. Perhaps something like this:
void process(Core* core, bool& done) {
for (int i = 0; i < core->size() && !done; ++i) {
if (!core[i]->is_taken()) {
process(core[i], done);
} else if (core[i]->is_taken() {
// done procesing
done = true;
}
}
}
// use via
bool done = false;
process(myCore, done);
In the version you have, the goingBack flag is passed by value, so every function gets its own copy and there is no way to pass the value of back to the parent in the recursive call chain. In my code above, done is passed as a reference, so changing the value at some point in the recursion chain will make it visible at parent scope (because the scope of the variable is outside the function itself). Hope this is more helpful.

How can we ensure that a while loop would not be an infinite loop?

This is a method where I am using the while loop. I strongly suspect that an infinite loop is possible. How to check and eliminate that?
I am using two while loops here. Sould I totally dismantle the while loop?
public class ReferenceListSaveHandler
{
public PublishReferenceListUpdates populateResponse(SearchQueryResponse pSearchQueryResponse,SearchQueryResponse pListResponse, ObjectFactory objFactory) throws IOException, ParserConfigurationException, SAXException,SipException, Exception
{
ReferenceDataProcessor lRefPro = new ReferenceDataProcessor();
PublishReferenceListUpdates lResponse = null;
Record listRecord = null;
ReferenceDataListItemListType lReferenceDataListItemListType = objFactory
.createReferenceDataListItemListType();
ReferenceDataListType lReferenceDataListType = null;
ReferenceDataListItemType lReferenceDataListItemType = null;
boolean ifSynonym = false;
String lRowIdObject = null;
final int lRowIdLength = 14;
if (refListItemItr.hasNext())
{
Record record = (Record)refListItemItr.next();
boolean continueProcessing = true;
boolean lastRecord = false;
while (continueProcessing)
{ // first use of while loop
if (refListItemItr.hasNext() || lastRecord)
{
continueProcessing = true;
lastRecord = false;
}
else
{
continueProcessing = false;
}
if (continueProcessing)
{
lSynonymListType = objFactory
.createSynonymListType();
Field itemLSIDField = record
.getField(ReferenceDataConstants.FIELD_COMPOUND_ASSET_ID);
if (itemLSIDField == null)
{
continue;
}
else
{
currentItemLSID = itemLSIDField
.getStringValue().trim();
}
lReferenceDataListItemType = objFactory
.createReferenceDataListItemType();
lReferenceDataListItemType = setListDetails(record,
lReferenceDataListItemType,
lId, lName, objFactory);
while (refListItemItr.hasNext()
&& continueProcessing)
{ // second use of while loop
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
continueProcessing = true;
}
}//while loop
}
}
}
Please help.
Problem number one: refListItemItr, whatever that is (its definition is not shown), has a .next() method but it's never called inside the loop.
Problem number two: The second while loop is always infinite if you enter it:
while (refListItemItr.hasNext()
&& continueProcessing)
{
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
Neither refListItemItr.hasNext(), nor continueProcessing can change inside this loop. That's why it's an infinite loop.
EDIT:
I can't tell you how to change the code because there are many possible ways to change it, depending on what's supposed to happen. You can try this but it may or may not work:
Remove the second loop entirely (it does nothing right now).
Add this line just before the end of the first loop:
record = (Record)refListItemItr.next(); // ADD THIS LINE
} //while loop BEFORE THIS LINE
This is an infinit loop , the outer loop depends on lastrecord which is not beeing set to true anywhere in the program
I throw in a loop counter whenever I write the word while, like this:
int loopCounter = 0, maxLoops = 1000; //just an example
while((loopCounter++) < maxLoops && (myConditions))
{
// loop away, this can't ever be infinite
}
or this
int loopCounter = 0, maxLoops = 1000; //just an example
do
{
// loop away, this can't ever be infinite
}
while((loopCounter++) < maxLoops && (myConditions))
Of course, maxLoops is always sized to be orders of magnitude greater than any reasonable number of iterations... Then I add a check:
if (loopCounter == maxLoops) { throw new InvalidOperationException("Infinite loop detected!"); }

Loop flow control

I have an array of objects, each object has a function that returns a Boolean value. What I need to do, is have a loop continuously running until each object returns a true value when the function is called on each object.
EDIT: Sorry I wasn't clear enough, I meant that I want the loop to break, when ALL of the objects functions return true.
Any ideas?
Java style syntax:
boolean good;
while (true) {
good = true;
foreach (MyObject o : myArray) {
if (!o.someFunction()) {
good = false;
break;
}
}
if (good) break;
}
I interpreted it as meaning that every object needed to have its function evaluated to true each time, and once they all evaluate to true break out of the loop.
If I got your question, you can do like this...
do
{
test = 0;
for(all functions)
{
char test_array[] = function_call();
}
int i = 0;
for(test_array.length)
{
if(test_array[i] == true)
{
count_no_true = i++;
}
}
if(count_no_true == no of function)
{test == 1;}
else
{test == 0;}
}while(test == 1)

Resources