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 3 of 3

Thread: Problem with nested for loops, Creating an array of Distinct ints from a larger array of ints.

  1. #1
    Junior Member
    Join Date
    Feb 2014
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Problem with nested for loops, Creating an array of Distinct ints from a larger array of ints.

    Hello all,

    FNG here, I read several posts, but they were referencing the boolean method. I need to create an array of distinct ints from a larger array of ints and then print both. I figured out how to do it with the boolean return method, but I have to do it with the "public static int[] saveDistinctNumbers(int[] array)" I think I'm good except for the nested for loops at the bottom.
    Thanks
    Chris

    This is where I'm stuck.
    When I enter 1 2 3 4 1 6 3 4 5 2
    It should return 1 2 3 4 6 5
    It is returning 1 2 3 4 0 6 3 4 5 2

    import java.util.Scanner;
    public class FML{
     
       public static void main(String[] args){
     
          Scanner kbd = new Scanner(System.in);
          int[] array = new int[10];
          int[] uniqueArray = new int[10];
          System.out.println("The program will accept integers and then"+
             " create \nand print an array of distinct integers.");
     
          for(int i =0; i<array.length; i++){
             System.out.print("\nEnter an integer: ");
             array[i] = kbd.nextInt();}
     
          uniqueArray = saveDistinctNumbers(array);
     
          for(int element: array){
             System.out.print (element + " ");}
     
          System.out.println ("\nDistinct");
     
          for(int element: uniqueArray){
             System.out.print (element + " ");}
     
       }
     
     
    //######################################################################################//   
     
       public static int[] saveDistinctNumbers(int[] array){
     
          int[] temp = new int[array.length];
          int counter = 0;  
         / /###############################################//
     
          for(int i = 0; i<array.length; i++){
     
             for(int j = 0; j < array.length;j++){              
     
                if (array[i]!= array[j]){                            
     
                   temp[i] = array[i];                               
                   counter++;}
     
                if (array[i]== array[j] && i!=j)
                   break;}
     
           //###############################################//
          }     
          int[] uniqueArray = new int[array.length];
     
          System.arraycopy(temp, 0, uniqueArray, 0, uniqueArray.length);
     
          return uniqueArray;
       }
    }
    Last edited by ChrisInPa; February 23rd, 2014 at 12:22 AM. Reason: correction


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,039
    My Mood
    Mellow
    Thanks
    184
    Thanked 647 Times in 634 Posts

    Default Re: Problem with nested for loops, Creating an array of Distinct ints from a larger array of ints.

    If i were to comment your code (Why don't you?), the method saveDistinctNumbers() might be described thusly:

    compares each element of the argument array to every other element of the argument array and saves in a temp array only the first occurrence of all elements - duplicates are rejected. returns the temp array of unique values when done.

    If you agree that that is what the method is trying to do, then compare the comment to what you've coded and see if the implementation matches the intent.

    I'm not sure what you mean by the "boolean method," but an alternative approach would be to attempt to add each element of the argument array to a temp array, only adding those values which have not already been added. That describes how a Set works.

    Both approaches include the added complications of sizing the temp array and then outputting only those elements of the temp array that were added from the argument array. For example, if the temp array is of the same size as the argument array but does not contain the duplicates of the argument array, then the number of values of interest in the temp array will be something less than the number of elements in the temp array. How do you know which elements of the temp array are extra?

    I'll assume that's the purpose of the 'counter' variable in your code, but it's not used to display the result. This highlights another occasion where comments that describe what your code is supposed to be doing would be helpful, possibly even indicating to you where a good thought was not completed.

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    ChrisInPa (February 24th, 2014)

  4. #3
    Junior Member
    Join Date
    Feb 2014
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problem with nested for loops, Creating an array of Distinct ints from a larger array of ints.

    In a word yes, and I usually do comment after I'm finished.

    This is what I came up with. It works fine, and will be perfect for me but surely there's a better way.

    Thanks,

    Chris

    import java.util.Scanner;
    public class FML{
     
       public static void main(String[] args){
     
          Scanner kbd = new Scanner(System.in);
          int[] array = new int[10];              // Test array
          String instr1 = "Enter 10 integers";    // instructions
          String instr2 = "\nInt: ";              // Loop instructions
          String reply =  "The Distinct numbers are: ";  // Distinct reply 
     
     
          System.out.print(instr1);  // instructions 
     
          for(int i =0; i<array.length; i++){  // get the ints
             System.out.print(instr2); 
             array[i]=kbd.nextInt();}
     
          int[]distinctArray = saveDistinctNumbers(array);  // Call the save distinct method
     
          System.out.println (reply); // initial reply
     
          for(int element: distinctArray){ // Print the distinct array
             System.out.print (element + " ");}
     
       }
     
       public static int[] saveDistinctNumbers(int[] array){
     
          boolean[] checker = new boolean [array.length]; // Bool array for finding distincts  
          int[] temp = new int[array.length];             //temp array to pass distinct to return 
     
          for(int i = 0; i<array.length; i++){      // uses bool array to id repeat ints  
             for(int j = 0; j < array.length;j++){  
                if(array[i] == array[j] && i != j)       
                   break;   
                if(array[i]!= array[j]){            // if is not a repeat
                   checker[i] = !checker[j];}}}     // makes the index at j true
     
          int truecount = -1;  //allows temp[]to move through index at a different rate than array[]
          int totalcount = -1; //allows array[] to move through index at a different rate than temp[]
     
          for (int element :array){           // for array[]
             totalcount++;                    //totalcount++  treated like i in a for loop
             if(checker[totalcount]){         // if checker[totalcount] is true
                truecount++;                  //truecount ++
                temp[truecount] = array[totalcount];}} //filters out the spaces between repeats
     
          int[] distinctArray = new int[truecount+1];              // properly formatted distinct array for return
          System.arraycopy(temp,0, distinctArray,0, distinctArray.length); //copy temp to distinct 
          return distinctArray;}  //return distinct.
     
    }

Similar Threads

  1. Replies: 41
    Last Post: February 21st, 2013, 04:42 PM
  2. Problem: Grabbing Ints from JTextField
    By Java Programmer in forum What's Wrong With My Code?
    Replies: 5
    Last Post: March 25th, 2012, 06:55 PM
  3. Reading ints into a multidimensional array
    By mju516 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 11th, 2012, 02:45 PM
  4. Binary Search for an array of random ints - Can't find the target value
    By mju516 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 30th, 2012, 10:25 AM
  5. Nested for loops and array
    By bryanboy in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 15th, 2011, 05:45 AM

Tags for this Thread