Results 1 to 2 of 2
  1. #1
    cachi is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default Return value of method

    Hi, How do i write a statement that checks the return value of a method in java. I have to do a conditional action based on the return value of true or false.
    How do i put this in an If statement and a while loop.
    Thanks

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    Here's a small example: filling an array with unique numbers.
    Java Code:
    import java.util.*;
    
    public class LoopTesting {
        public static void main(String[] args) {
            Random rand = new Random();
            int seed = 20;
            int count = 0;
            int[] vals = new int[10];
            // Initialize elements with -1 to avoid value of zero.
            Arrays.fill(vals, -1);
            // Fill the vals array with unique numbers [0 - 19].
            while(count < vals.length) {
                int next = rand.nextInt(seed);
                if(isUnique(next, vals))
                    vals[count++] = next;
            }
            System.out.printf("vals = %s%n", Arrays.toString(vals));
        }
    
        private static boolean isUnique(int n, int[] array) {
            for(int j = 0; j < array.length; j++) {
                if(array[j] == n)
                    return false;
            }
            return true;
        }
    }

Similar Threads

  1. Replies: 3
    Last Post: 06-05-2010, 08:05 PM
  2. return a null method
    By valoyivd in forum New To Java
    Replies: 2
    Last Post: 04-21-2008, 11:19 PM
  3. Replies: 2
    Last Post: 04-16-2008, 12:35 PM
  4. Return question in a method.
    By MetalGear in forum New To Java
    Replies: 1
    Last Post: 01-13-2008, 04:45 AM
  5. if..else..return
    By mqdias in forum New To Java
    Replies: 1
    Last Post: 08-10-2007, 04:20 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •