Comparing array elements for equality

Hi
I have written a simple program that works as a lottery number predictor. It works fine except for the fact that sometimes 2 numbers will be the same. Does anyone know of a method that compares an array element to the others to test for equality?

ok I've had a go at implementing a solution. I worked it out on paper so I haven't tested it yet in the program. Let me know if you can see any errors that I can't.
   boolean numNotSame = true;
   int[] lottery = new int[5];
   int currentNumber;
   start:  //label to return to if 2 numbers are the same
   while(numNotSame){
      for( int j = 0; j < lottery.length; j++){
          currentNumber = 1 + randomNumbers.nextInt(34);   //get random number
          for( int i = 0; i < lottery.length; i++){
             if( currentNumber == lottery)
continue start; //if numbers are the same begin again
} //end inner for
lottery[ j ] = currentNumber; //set array element if number not used yet
} //end outer for loop
numNotSame = false; //set false so while loop will end
} //end while block

Similar Messages

  • Comparing input value to array value for equality

    Hi all,
    I'm fairly new to java and I am finding this forum to be a great resource. I am learning more by seeing the problems others are having and the solutions. thanks ahead of time for the help.
    Here is my problem.
    I am using InputStreamReader and Buffered Reader to take keyboard input and add to a string ( lets call it name)
    I then search an array for a match
    for ( int i=0; i<array.length; i++
    if ( name == array[i] )
    blah blah blah
    I can compile and run but my input never matches a value I know is in the array.
    Do I need to do something to the input string to make it usable?
    Any insight would be much appreciated

    When comparing objects (including Strings) you usually want to use obj1.equals(obj2), rather than obj1 == obj2. The equals method uses semantics defined by each object to determine whether the contents are "equal". For Strings it compares the characters, for a MyEmployee class it could compare employee IDs or names, birthdates, and whatever else you decide is important.
    The == operator, when used on references (anything that's not a primitive like int, float, etc.), tests whether both references refer to the same object. In your case, name and array[j] may have the same contents, but they're stored in two different String objects, so the == test fails.
    Oh, and when you post code, use [ code ] blocks to format it, and don't use i as an array index (gives you italics) See
    http://forum.java.sun.com/faq.jsp#messageformat

  • How compare two URLs for equality if one uses jar protocol?

    I'm trying to see if some URLs are referring to the same jar file but some of them come with the prepend/append of "jar:file:/" and "!/" and some are just as "file:/". So when I call "URL.equals(...)", it returns false. How do I properly compare these two?
    //Returns false, even though both can be used to find the jar file
    new URL( "jar:file:/home/me/tmp.jar!/" ).equals( new URL( "file:/home/me/tmp.jar" ) );

    The URL with the leading "jar:" and trailing "!/" is a JAR URL. It's described in the JarURLConnection class API document.
    This is one way (there any be a simpler one). You will have to figure out whether you're working with a jar URL or a "regular" URL by parsing the URL to figure out which kind it is. One diffrence is the leading "jar"
    import java.io.IOException;
    import java.net.JarURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    public class Xy
        public static void main(String[] args)
            throws MalformedURLException, IOException
            URL fileURL =
                new URL("file:/Program Files/Java/jre6/lib/deploy.jar");
            URL jarURL =
                new URL("jar:file:/Program Files/Java/jre6/lib/deploy.jar!/");
            String fURL = fileURL.toString();
            System.out.println("fileURL: " + fURL);
            String jURL = ((JarURLConnection) jarURL.openConnection()).
                getJarFileURL().toString();
            System.out.println("jarURL: " + jURL);
            if (fURL.equals(jURL))
                System.out.println("They are equivalent");
    }

  • Comparing two ResultSets for equality

    Hello,
    I wish to test if two separate ResultSet objects are identical.
    By identical I mean that two different ResultSet objects are identical if
    they contain the same rows in the same order, and each row contains identical values in the two ResultSets.
    Two possibilities could be that the equals() method returns true or that the hashcode() method also produces the same hash value if the objects are identical as described.
    I haven't been able to find any documentation on this issue.
    Does anyone know if either (or both) of these methods have the contract as described above? If so are they guaranteed?
    I can see several potential problems here. Performance with a large ResultSet, duplicate rows, and the ordering of rows not being guaranteed?
    Thanks in advance.
    Tim

    Two possibilities could be that the equals() method
    returns true or that the hashcode() method also
    produces the same hash value if the objects are
    identical as described.I can tell you without looking anything up that these methods do not do that, as doing that would require them to scan the entire result-set, and JDBC tries to avoid doing useless processing. You are going to have to write this code yourself.

  • Comparing dates for equality using API

    Hello,
    I was wondering if you could help me understand if it is possible for me to compare two dates for equality.
    I am looking to only compare the date and the month. So, if I am checking "today" with another objects Date for equality, it obviously fails because the compareTo and the equals method of both Date and Calendar, I think, are comparing even the timestamps.
    here is something I wrote for testing, which obviously is of no use
    Calendar today = Calendar.getInstance();
    Calendar later = Calendar.getInstance();
    later.set(Calendar.HOUR, 03);
    System.out.println(today.getTime());
    System.out.println(later.getTime());
    if(today.equals(later)){
       System.out.println("BIG BANG");
    if(today.compareTo(later)<0)
       System.out.println("Today Date is Lesser than my Date");
    else if(today.compareTo(later)>0)
       System.out.println("Today Date is Greater than my date");
    else
       System.out.println("Both Dates are equal");   
    Date today = new Date();
    Date myDate = new Date();
    myDate.setHours(23);
    System.out.println(today);
    System.out.println(myDate);
    if(today.compareTo(myDate)<0)
       System.out.println("Today Date is Lesser than my Date");
    else if(today.compareTo(myDate)>0)
       System.out.println("Today Date is Greater than my date");
    else
       System.out.println("Both Dates are equal");   
       So is then the only way left, is using the simple date formatter and going about things ?

    package forums;
    import java.util.Calendar;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public class CalendarExample
      private static final DateFormat DF = new SimpleDateFormat("yyyy-MM-dd");
      public static void main(String[] args) {
        Calendar today = Calendar.getInstance();
        Calendar later = Calendar.getInstance();
        later.set(Calendar.HOUR, 3);
        System.out.println("today="+DF.format(today.getTime()));
        System.out.println("later="+DF.format(later.getTime()));
        System.out.println("isSameDayAndMonth(today, later) = "+isSameDayAndMonth(today, later));
        System.out.println("\n");
        Calendar tomorrow = Calendar.getInstance();
        tomorrow.set(Calendar.DATE, tomorrow.get(Calendar.DATE)+1);
        System.out.println("today="+DF.format(today.getTime()));
        System.out.println("tomorrow="+DF.format(tomorrow.getTime()));
        System.out.println("isSameDayAndMonth(today, tomorrow) = "+isSameDayAndMonth(today, tomorrow));
        System.out.println("\n");
      public static boolean isSameDayAndMonth(Calendar a, Calendar b) {
        return a.get(Calendar.DATE) == b.get(Calendar.DATE)
            && a.get(Calendar.MONTH) == b.get(Calendar.MONTH)
    }You're welcome... Javas standard date libraries leave a lot be desired. I recommend you try Joda, which is [a long standing JSR, which has never gotten up|http://www.theserverside.com/news/thread.tss?thread_id=44248].

  • Using a For Loop Index for Array Element Number?

    Hi.  Thanks in advance for the help.  I can't seem to find what I want to do here using the search function... probably because I don't know how to frame the question appropriately.  Ignore the title to this post cause it's probably wrong vocabulary for what I want to do.
    Here's the situation:
    I have a 2D array where the first column is the X data and each subsequent column is Y data (call it Y1...Yn).  The n-value varies from run to run (some runs have 4 columns of data, some have 20), but that is easily gathered when reading the data file.  I need to perform a number of operations on each set of data, the least of which is smoothing the data and graphing it, so I'm limiting my discussion to these 2 operations.
    What I want is a for loop structure where the indexing of the loop tracks the Y1...Yn columns, grabs each column for the iteration, performs the relevant analysis, and spits out the result, but in a stackable manner.  Thus the title; I want to use the for loop's index to mark the array element for building a new array.
    See the image attached.  A 2D array of 9 columns (X, Y1...Y8) is analyzed such that each data set, (X, Y1), (X, Y2)...(X, Y8) is bundled, graphed, run through a B-spline Fit, of which is also graphed.  I need to replace this with something that looks like the for loop structure shown.  
    I just don't know how to get those two data bundles [(X, Yi) and it's smoothed pair] out of the for loop in a stacked set from every iteration of the for loop.
    Again the title, I think I want to build a new array where i use the index of the for loop to control the entries of the new array.  But I can't see how to do that.
    Any help would be appreciated.
    Attachments:
    NeedForLoopForThis.PNG ‏30 KB

    Hello H.R. Dunham, and welcome to the forum!
    It seems that you may be looking for Auto-Indexing, a basic feature of loops in LabVIEW.  You'll need to transpose your array before wiring it into the for loop, as elements are auto-indexed by row before column, but at that point you should be able to operate on each column and output an array of n cluster elements corresponding to your input columns.  Auto-indexing tunnels look like brackets to indicate each element will be indexed automatically- this should be the default when wiring an array into a for loop or when wiring anything out of a for loop.
    As for how to build your pairs, I suggest removing the X column and creating a "starter" cluster containing your X data and placeholder Y data before entering your "Y" processing loop.  Use the bundle by name function in the for loop to insert your processed column data into the cluster and auto-index the cluster output. Flow would be something like this:
    1) Gather data
    2) Split X and Y using standard array operations
    3) Create "template" cluster with shared X data
    4) Pass template cluster and Y-column array into an auto-indexed for loop.
    5) Insert processed Y data into cluster inside loop.
    6) Auto-index cluster data out of loop.
    This tutorial is probably also a good place to get started:
    Getting Started with NI LabVIEW Module 3: Loops
    http://www.ni.com/white-paper/7528/en/
    Hope that helps!
    Regards,
    Tom L.

  • How to save the array elements

    hi,every body
    I need to save the array elements,for later use,can you tell me how?

    here you go.
    Message Edited by Root Canal on 10-21-2008 02:50 PM
    global variables make robots angry
    Attachments:
    write some stuff and read some stuff.vi ‏47 KB
    write some stuff and read some stuff.PNG ‏19 KB

  • Build 1D array using for loop

    Hi guys,
    I am testing out array. How do I create a 1D array of x-y using for loop?

    Nextal wrote:
    I am testing out array. How do I create a 1D array of x-y using for loop?
    OK, first of all you did not say what the array should contain. If you want an array that has one array element for each iteration of the while loop, you need to first think a bit harder. Your outer loop has no wait, thus it will spin millions of times per second and you will run out of memory soon, no matter how much memory you have. How many times should the while loop iterate? If you know the number before the program starts, you would use a FOR loop and autoindex at the loop boundary.
    If you want to use a whiile loop, you need a mechanism to keep the array size reasonable. For small final arrays, you can just build the array in a shift register if you need it updated as it happens. If you only need the array after the loop stops, you can autoindex at the right loop boundary.
    In any case, you should take a step back and decide what you really want. Currently the specifications are very vague and unreasonable.
    LabVIEW Champion . Do more with less code and in less time .

  • Using a For loop to call one array element at a time

    I have been working on a VI that reads a GPS unit, parses the data, outputs what I need, compares the actual GPS location to the desired location, determines a desired heading and moves on from there.  My question pertains to the number of desired locations I can input right now.  I need to be able to input a predtermined number of locations (not just the one that I can input right now).  I was told that it is possible to use a For Loop with an array and have the first set of Lat and Long values run through the VI and when everything is complete that the next set of values will be chosen.  Does this mean that I need to put the entire VI inside a For Loop and have the array update as soon as the VI has completed its first mission?  I understand the concept of how this work from other programming languages but I'm not sure how to implement the solution in LabVIEW.  Any help would be appreciated.
    Adam

    adamoutlaw wrote:
    Here is a portion of the VI.  I need two separate arrays, one for Latitude and one for Longitude, of the same size.
    I don't see any arrays in your code. Do you want to generate arrays form individual data points or do you want to process arrays, one element at a time? Both can take advantage of autoindexing. Here's a simple picture.
    Your VI contains a weird mix of DBL and EXT precision. Most likely all you need is DBL. Keep your representations consistent!
    Message Edited by altenbach on 08-02-2007 07:14 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Indexing.png ‏4 KB

  • Comparing objects for equality with UDT's

    Hi.
    I was wondering how Oracle does comparison for equality of objects that contains parameters of user defined types.
    Suppose I have an object with a parameters whose types are:
    1) number,
    2) varchar2,
    3) nested table type,
    4) associative array
    and I want to compare two such objects for equality. Would Oracle compare all parameters of this 2 compared objects field-by-field (and dig recursive to "leafs"), or would it compare only 1), 2) and doas nothing with 3) and 4)?
    Must I declare an order method for such comparison?

    You didn't specify a version - this is correct for 10.2, I'm not sure if it has changed in 11g.
    By default it will compare for exact equality - i.e that every attribute is the same. You can also only do it in SQL, not PL/SQL. Also can only do = and <> - you cannot do < or > etc.
    You need to create a MAP or ORDER method on the type to do any more sophisticated comparison (Same as in most object oriented languages). Documentation is here http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14260/adobjbas.htm#sthref211

  • Array elements equal to each other?

    Hi,
    Maybe a very simple question but i haven't found the answer here...
    I have a 1D Array with let's say 4 elements, and if all elements are equal to each other
    (1,1,1,1)  then it should return true
    if one element is other then the rest
    (1,2,1,1)  it should return false...
    How to build this simple?
    Best regards,
    Thijs
    Solved!
    Go to Solution.

    Hi Thijs,
    you need to compare one element of the array with the remaining ones:
    To your own approach:
    - RubeGoldberg due to indexing the same element of the array in each iteration
    - RubeGoldberg due to using a loop where polymorphism will do the same
    - wrong labeling of the output: you need to AND all booleans, but not ORing them
    - the AutoCleanup tool is pretty good at such small snippets…
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • "In initializer for 'mxmlContent', type Object is not assignable to target Array element type..."

    Hi all,
    So I've have built an application on flash builder 4.5 using Christophe Coenraets' tutorial "Building an EmployeeDirectory" (http://www.adobe.com/devnet/flex/articles/employee-directory-android-flex.html#articlecont entAdobe_numberedheader).
    I'm getting this error message "In initializer for 'mxmlContent', type Object is not assignable to target Array element type mx.core.IVisualElement." and then the debugger highlights my code this line of my code "</s:List>" in my EmployeeDetails.mxml file. This started after I coded Part 5, Step 2 "Integrating with the Device Capabilities: Triggering the Actions".   The rest of the code debugged fine.
    I think it relates to Christophe's note "Note: Make sure you import spark.events.IndexChangeEvent (and not mx.events.IndexChangedEvent) for this code to compile.".  I don't know where to place this
    " import spark.events.IndexChangeEvent;" line of code. 
    Any help?  Tks in advance..
    Any help would be greatly appreciated.  Thanks

    You have a DataGrid directly inside a State element. Perhaps wrap it in an AddChild element?
    More information on using states can be found here:
    http://livedocs.adobe.com/flex/3/html/help.html?content=using_states_1.html

  • Failed to compare two elements in the array

    very often, I have the error "Failed to compare two elements in the array" in Exchange 2013 ECP. We are not running DAG. I google a bit but don't get a lot of result on this.
    I was trying to track mail from a user who send to DL group. Since I can't do in in ECP , how can I do it in EMS?

    I too have this issue.  I'm not sure how wide spread.  I know of one user who sends emails regularly to a DL named "All Users" which is a Security Group which we then add real users to and not just every mailbox.  When he sends the emails,
    from his perspective, everything is fine, meaning he gets to NDR or anything.  Also, when he adds the Dl in Outlook To field and expands it, all the correct users are there.  In fact, it tells him there are 203 addresses here.  However, only
    184 are actually getting the message.  When I try the EAC to view the tracking report, it will show the message, but if I click on the edit button, I get "Failed to compare two elements in the array".  If I try from EMC with search-messagetrackingreport
    -identity "recipient address" -sender "sender address" -bypassdelegatechecking and the recipient address is the group, it says it could not be found.  If I try with simply putting an email address of someone who is a member of that group, it says Warning:
    An unexpected error has occured and a Watson dump is being generated.  Failed to compare two elements in the array.  I don't know what else to try.  Anybody??

  • 'Incorrect value type for array element in index N'

    Please help.  Preflight is flagging multiple 'Incorrect value type for array element in index N" > Required key /F is missing >Array element at index 0 is of wrong type' messages for pages throughout my text document with embedded navigation and annotations.What does it mean? Is there anything I can do?
    The origins of the file are from a selection of emails taken from Mail and gmail, and letters probably written on pc (Office) and converted to pdf...
    I'm on Mac Mavericks.
    Thanks for reading.

    What problem are you trying to solve with preflighting? What are you checking for?

  • Type defined array of clusters for holding configuration data - setting default values for each array element

    Hi,
    I was wondering if I could get some information and opinions about using a type defined array of clusters to hold configuration data.  I am creating a program to test multiple DUTs and wanted to have a type defined control for each DUT containing the information needed to create the DAQmx tasks for all of the signals for that DUT.  I am wanting to do this so that the data is hard-coded and not in a file that the user could mess up.
    The type def controls are then put in a subVI that chooses the appropriate one based on the DUT Type enumeration wired to a case structure.  
    I am having problems with the type defined control.  I am seeing issues when attempting to save a unique configuration to each array element in the array of clusters.  Somehow it worked to begin with, but now clicking "Data Operations --> Make Current value default" on individual elements of the cluster or the entire cluster (array element) is not saving the data when I re-open the type def control.  What am I doing wrong?  Am I trying to do something with arrays of clusters that I should not be doing?
    I have attached one of the type defined controls for reference.  I tried changing it to Strict to see if that helped, but no luck.
    To reproduce, change the resource string for array element 0 and make the new value the default value.  Then close the type def, and re-open it.  The old value is still present in that element.  The VI is saved in LabVIEW 2012.
    Solved!
    Go to Solution.
    Attachments:
    CM_AnalogInputs.ctl ‏11 KB

    Values of a typedef are not proprigated to instances of the control. THey will pick it up if created AFTER the data values have been changed. THey will not get updated with future changes. You should either create a VI specifically for hardcoding your values or implement a file based initialization. The file based would be much better and more flexible. If you don't want users to modify the data simply encrypt it. There is a noce blowfish library you can download.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

Maybe you are looking for