Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dermine if a value of type int is a match in an array?

Here is the code I have so far

    int []d = {2,18,4,4,6,8,10}; 
    int matchNumber = 4 ;
    i=0 ;

    for(i= 0; (match==d[i])&&(i < MAX_SIZE-1); i++); 
    { 
    if(matchNumber==d[i]) 
    { 
    System.out.println("Match number " + matchNumber + " appears in array d at index " + d[i]);

    }
    else 
    {

    System.out.print("-1");}
    }

If the int is a match I have to display the first index it appears in the array, if not I have to display -1. It seems like this is how it should be written but I just keep getting a -1 as an answer. How do I keep the same type of format because I am limited on what I can use to get the correct output.

like image 416
user3006939 Avatar asked Jan 21 '26 01:01

user3006939


1 Answers

1) Appears at index i not d[i]. That's the problem. i is your index. That's what you want printed out, not the value, d[i]. I the index is printed, break the loop.

2) Also, you shouldn't have the println("-1"); inside the loop. You only want it printed out if the value is not found. So I added a boolean statement. If the value is found it eqauls true. If not found, then I have a print statement to print -1.

3) Also, maybe you just want i < d.length as you stopping statement in the loop.

4) Another huge problem is the ; at the end of your for loop. I fixed that too. The ; ends the loop even before it starts.

5) Also, you don't need the i = 0 outside of your loop. I added the int i = 0 declaration inside of the loop. If you wanted to keep it the way you had, then the i = 0 should be int i = 0;

int []d = {2,18,4,4,6,8,10}; 
int matchNumber = 4 ;
boolean found = false;
for(i= 0; i < d.length; i++)
{ 
    if(matchNumber==d[i]) 
    { 
        System.out.println("Match number " + matchNumber 
                       + " appears in array d at index " + i);
        found = true;
        break;

    }
}

if (!found) System.out.println("-1");

Edit: Using a while loop

int []d = {2,18,4,4,6,8,10}; 
int matchNumber = 4 ;
boolean found = false;

int i = 0;
while (!found && i < d.length) {
    if (matchNumber == d[i]){
        System.out.println("Match number " + matchNumber 
                          + " appears in array d at index " + i);
        found = true;
    }
    i++;
}

if (!found) System.out.println("-1");
like image 115
Paul Samsotha Avatar answered Jan 22 '26 17:01

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!