Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Array that tests if any elements repeat themselves

  1. #1
    Member
    Join Date
    Aug 2012
    Posts
    67
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Array that tests if any elements repeat themselves

    Hey guys, I am trying to write a program that takes an array of float values and determines if all the numbers are different for each other. I am trying to set a temp variable that stores the value of the current element in the array and compares if to the next one. If they match, then break the loop and return false.

    However, I get an exception. What did I do wrong?

    package Creativity3;
     
    public class FloatingArray
    {
    	public static void main(String[] args)
    	{
    		float[] array = new float[3];
    		array[0] = 1; 
    		array[1] = 3;
     
    		System.out.println(FloatingArray.isDifferent(array));
    	} 
     
    	public static boolean isDifferent(float[] array)
    	{
    		float temp;
    		boolean count = true;
    		if(array.length == 0)
    		{
    			throw new IllegalArgumentException("Array can't be empty!");
    		}
     
    		else
    		{
    			for(int i = 0; i <= array.length - 1; i++)
    			{
    				temp = array[i];
    				if(temp == array[i + 1])
    				{
    					count = false;
    					break;
    				}
    			}
    		}
    		return count;
    	}
    }

    Exception:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Creativity3.FloatingArray.isDifferent(FloatingArra y.java:28)
    at Creativity3.FloatingArray.main(FloatingArray.java: 11)
    Thank you.


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Array that tests if any elements repeat themselves

    What's going to happen on the indicated line

    			for(int i = 0; i <= array.length - 1; i++)
    			{
    				temp = array[i];
    				if(temp == array[i + 1]) // ***** here
    				{
    					count = false;
    					break;
    				}
    			}

    when i = array.length - 1?

    Another problem is that of your logic. Remember that floating point numbers are not represented on digital computers with 100% precision (or is it accuracy? I get the two confused!), and so testing for equality can be problematic. You'd be much better off using ints or if you can't use ints, then use doubles which allow for more significant digits than floats, and test not for equality, but for being "close enough".

    One way would be to test for equality like this:

    public static boolean closeEnough(double expectedValue, double observedValue) {
       if (expectedValue == 0.0) {
          return EPSILON < Math.abs(expectedValue - observedValue);
       } else {
          return EPSILON < Math.abs((expectedValue - observedValue) / expectedValue);
       }
    }

    Where EPSILON is a constant double of small value.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Array that tests if any elements repeat themselves

    java.lang.ArrayIndexOutOfBoundsException: 3
    at Creativity3.FloatingArray.isDifferent(FloatingArra y.java:28)
    At line 28 the index to the array goes past the end of the array. Check the code to see how the index got past the end of the array.
    Remember that array indexes range from 0 to the array's length-1
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Member
    Join Date
    Aug 2012
    Posts
    67
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Array that tests if any elements repeat themselves

    Quote Originally Posted by Norm View Post
    At line 28 the index to the array goes past the end of the array. Check the code to see how the index got past the end of the array.
    Remember that array indexes range from 0 to the array's length-1
    I put array.length - 2 and it worked thanks.

  5. #5
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Array that tests if any elements repeat themselves

    It may not work as well as you think. The logic I believe will require *nested* for loops. Test your code out on some arrays and see for yourself. Your current code only appears to work for same numbers next to each other in the array.

  6. #6
    Member
    Join Date
    Aug 2012
    Posts
    67
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Array that tests if any elements repeat themselves

    Quote Originally Posted by curmudgeon View Post
    It may not work as well as you think. The logic I believe will require *nested* for loops. Test your code out on some arrays and see for yourself. Your current code only appears to work for same numbers next to each other in the array.

    I tried to do another for loop but this one always gives me false (reasonable, considering that if I loops through it I will always find the value that I stored in temp. How do I fix this?

  7. #7
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Array that tests if any elements repeat themselves

    Think of the algorithm first, how you would solve this on paper if you had a large collection of numbers. You'd walk down the list, first seeing if there are duplicates of the first number in all the numbers *above* it, then seeing if there are any duplicates of the second number in any numbers *above* it, then checking the third number against all the numbers *above* it,... do you see the logic inherent in this process?

  8. #8
    Member
    Join Date
    Aug 2012
    Posts
    67
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Array that tests if any elements repeat themselves

    Quote Originally Posted by curmudgeon View Post
    Think of the algorithm first, how you would solve this on paper if you had a large collection of numbers. You'd walk down the list, first seeing if there are duplicates of the first number in all the numbers *above* it, then seeing if there are any duplicates of the second number in any numbers *above* it, then checking the third number against all the numbers *above* it,... do you see the logic inherent in this process?
    I think that this one should work, but for some reason it doesn't. Does anything clear seem wrong now again?

    	public static boolean isDifferent(float[] array)
    	{
    		float temp;
    		boolean count = true;
     
    		if(array.length == 0)
    		{
    			throw new IllegalArgumentException("Array can't be empty!");
    		}
     
    		else
    		{
    			for(int i = 0; i < array.length; i++)
    			{
    				temp = array[i];
    				for(int c = i + 1; c < array.length; c++)
    				{
    					if(i != c && array[i] == array[c])
    					{
    						count = false;
    					}
    				}
    			}
    		}
    		return count;
    	}

  9. #9
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Array that tests if any elements repeat themselves

    Quote Originally Posted by jean28 View Post
    ... but for some reason...

    So, what if the array contains [1.0, 3.0, 0.0]? What would you expect? What does it give?

    What if the array contains [1.0, 2.0, 3.0, 2.0, 5.0, 6.0]? What would you expect? What does it give?

    Well, I'll create a couple of arrays and print out each array and result from your method...

    import java.util.*;
     
    public class FloatingArray {
        public static void main(String [] args) {
            float [] x = {1, 3, 0};
            System.out.println("x = " + Arrays.toString(x));
            System.out.println("FloatingArray.isDifferent(x) = " + FloatingArray.isDifferent(x));
            System.out.println();
     
            float [] y = {1, 2, 3, 2, 5, 6};
            System.out.println("y = " + Arrays.toString(y));
            System.out.println("FloatingArray.isDifferent(y) = " + FloatingArray.isDifferent(y));
     
        } // End of main
     
        public static boolean isDifferent(float [] array) {
            .
            .
            .

    Output

    x = [1.0, 3.0, 0.0]
    FloatingArray.isDifferent(x) = true

    y = [1.0, 2.0, 3.0, 2.0, 5.0, 6.0]
    FloatingArray.isDifferent(y) = false


    Are the outputs for these examples correct? (I think they are.)


    Bottom line:
    How about showing us an example for which you think it gives an incorrect result? Maybe someone can walk you through it...



    Cheers!

    Z

Similar Threads

  1. How to sum up elements in an array?
    By D-X69 in forum Java Theory & Questions
    Replies: 2
    Last Post: May 28th, 2012, 01:21 AM
  2. [SOLVED] How To Increment Array Elements
    By Nuggets in forum Java Theory & Questions
    Replies: 15
    Last Post: April 1st, 2012, 12:10 PM
  3. Missing elements in array
    By frozen java in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 10th, 2012, 11:52 PM
  4. Help camparing array elements
    By Richmond in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 8th, 2012, 12:23 AM
  5. Array elements comparison
    By Pradeep_Parihar in forum Java Theory & Questions
    Replies: 1
    Last Post: December 10th, 2011, 09:45 AM