troubleshooting Question

Matching a number to an element of an integer array.

Avatar of Flex Tron
Flex TronFlag for United States of America asked on
Java
27 Comments1 Solution176 ViewsLast Modified:
Dear Gurus,
I am new to Java and trying to write a code where need to match a number 'y' from an array list x[].
If teh number matches, it should give the index value else return the value '-1'
I have written the code and it works...except that when the value doesn't match, it returns '-1' multiple times.
Is there a way that it returns '-1' only once.? Thankyou !

import java.io.*;
public class findLast {
    public static void main(String[] args) {
        try {
            boolean matchFound = false;
            int[] x = {7, 8, 9, 10, 11, 12};
            int y = 4;

            for (int i = x.length - 1; i >= 0 && matchFound == false; i--) {
                if (x[i] == y) {
                    System.out.println("Index is " + i);
                    matchFound = true;
                }
                else if (matchFound == false){
                    System.out.println(-1);
                }
            }

        }
        catch (NullPointerException e) {
            System.out.print("NullPointerException Caught");
        }
    }
}

Output:
C:\MS\src>java findLast
-1
-1
-1
-1
-1
-1
ASKER CERTIFIED SOLUTION
krakatoa

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 27 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 27 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros