简体   繁体   中英

Using try-catch with a if else loop

So I am making a program which takes an int input from the command line and then searches the array in the program for the int and if found, return the index of the number. If not, then it throws an exception stating that it wasn't found and end the program. This is what I have so far:

public static void main(String[] args) {

    int[] intArray = {9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23};
    System.out.println(Arrays.toString(intArray));

    int intArgs = Integer.parseInt(args[0]);

    System.out.println("Your entered: " + intArgs);

    FindNum(intArray, intArgs);
}

public static int FindNum(int[] intArray, int intArgs) {
    for (int index = 0; index < intArray.length; index++){
        try{
            if (intArray[index] == (intArgs))
                System.out.println("Found It! = " + index);
            else 
                throw new NoSuchElementException("Element not found in array.");
        } catch (NoSuchElementException ex){
            System.out.println(ex.getMessage());
        }
    }
    return -1;      
}

While this sort of works and can find the index, it throws the exception for each number in the array instead of just one for the whole array. And if it finds the number in the array, then it replaces one of the lines with the confirmation line from the loop. Example output for 66:

[9, 97, 5, 77, 79, 13, 7, 59, 8, 6, 100, 55, 35, 89, 74, 66, 32, 47, 51, 88, 23]
Your entered: 66
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Found It! = 15
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.
Element not found in array.

How can I make it so that when it finds the number, it only prints the index line and vice versa for the exception. I feel it may have something to do with the loop but not sure what I can do to prevent that.

searches the array in the program for the int and if found, return the index of the number. If not, then it throws an exception stating that it wasn't found and end the program.

Read what you wrote carefully.

If not found, you should throw an exception. You only know you haven't found the value once you have gone through all its elements. So you can't throw from inside the loop. You can only throw after the loop, if you haven't found the element.

Second, you're supposed to throw the exception. You're not doing that: instead, you throw and catch the exception you've just thrown. The point of throwing an exception is to let the caller of the method know that something exceptional happens. You shouldn't throw and catch an exception inside a method.

Finally, your method is supposed to return the index. But it doesn't. It always returns -1.

You can rewrite the code like below..

As per your code, you are checking each element and if not matching, you are throwing an exception. This is not accurate, since you cannot conclude if the element not exist unless you scan all elements. In that case you can use flags to determine if you find a match and after the for loop you can check the flag and throw an exception. Again, if you are planning to catch the exception within the same method, you may not need to throw the exception after all. Instead you can simply return the index or -1 like below..

public static int FindNum(int[] intArray, int intArgs) {
   for (int index = 0; index < intArray.length; index++){
        if (intArray[index] == (intArgs)){
            System.out.println("Found It! = " + index);
            return index;
        }
   }
   throw new NoSuchElementException("Element not found in array.");
}
int i = -1;
...
    if (intArray[index] == intArgs) i = index;
...

Try to make an int variable to keep an index of the found element. The last line of the method throws an exception if nothing is found.

if (index == -1) throw new NoSuchElementException(...);

Another way is returning the index directly and throwing an exception in the end without any conditions.

    if (intArray[index] == intArgs) return index;
...
throw new NoSuchElementException(...);

I advise you not to return the error code. More natural for Java, in this case, is throwing an unchecked exception.

Remove the else and throw statement inside the try. Initialize a variable boolean flag=false. before iteration. If the element is found inside the loop, add condition flag=true and then break from loop. Now after the end of iteration write this : if(!flag) System.out.print("Element not found"); basically you are printing the element not found on every iteration except where the element gets founds which is a terrible error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM