Sunday 15 July 2012

java - Avoiding Null pointer when single value needs to be returned -


First, there are several questions on stack overflow at zero pointers - but this one could not be found. It exists and I can not find it, so please leave my mistake.

The question is normal - if a function returns only one element then how to deal with the wrong 'element' case. Example: Sample code is just a sample.

  The public int search is the largest number of int x [int, int x] {// what is the logic if numfound {smallesNumberGreaterThanX; } what else ?? }}   

If there is no array more than X-ray - then what to do?

  1. Refers to the empty Java table instead of zero Pointer - but is it an array capable if the function returns an element?

  2. The next option is empty, I have seen many posts that reject the idea of ​​returning.

  3. The third item is to be recovered [Boolean found; Intestine value; } It looks like an Overkill.

    Please suggest me the best way.

    I see many ways to solve this problem. I suggest to avoid (1) or (2), and (3) and (4).

    (1): Your way will be the exception:

      Public int search worstmountGreaterThanX (int a [], int x) NoSuchNumberException throws {// what ever logic is. If (numfound) {smallest number GreaterThanX; } And (new) NoSuchNumberException (); }}   

    and being asked

      try {int smallestNum = findSmallestNumberGreaterThanX (a, x);   

    You must also create a Class NoSuchNumberException:

        code> public class NoSuchNumberException exception extension {public NoSuchNumberException () {} Public NoSuchNumberException (String Message) {Super (Message); }}   


    (2): Refresh your code a bit.

    Instead of doing everything in the same way, make the method

      the public int search the largest number (int a []) {...}   

    And then say

      int smallestNum = findSmallestNumber (a); If (Smallest News; x) {// Use Smallest News} In other {// handles case, where no small number & gt; X}   


    (3): Set your return type to round, and return empty. Java will automatically enter between integer and integer, and zero is a valid value for integer. Be sure to check the spaces wherever you use this method, because if you try to put an end to an intern, it will be broken.


    (4): Return less than x numbers. (I strongly recommend that you do not use this solution until you can use that number in any way.) Since the number is less than x, it can be identified as the state of an error .

No comments:

Post a Comment