0

Had no luck the first time I had posted my question so I thought I would try again. I am a new Java programmer working on a little segment of code currently. In short I have created an array and a variable, what I would like this program to do is take the array and variable, pass it down to a method, have the method look at the array and if any of the numbers in the array are the same as the variable "8", take them out of the array "create a new array" return this array back to main and print it out.

I would like the array {2,4,8,19,32,17,17,18,25,17,8,3,4,8} to display {2,4,19,32,17,17,18,25,17,3,4} after being passed back to main please explain to me what I am doing wrong keep in mind I am brand new to java.

public class Harrison7b
{
   public static void main(String [] args)
   {
      int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
      int varB = 8;
      // Call with the array and variable you need to find.
    int[] result =  newSmallerArray(arrayA, varB);

    for(int x = 0; x < arrayA.length; x++)
    {
      System.out.print(arrayA[x] + " ");


    }

   }

   public static int[] newSmallerArray( int[] arrayA, int varB)
   {
      int count = 0;   

      for(int x = 0; x < arrayA.length; x++)
      {
         if(arrayA[x] == varB)
         {
            count++;
         }
      }
         int [] arrayX = new int[arrayA.length - count];

         int index = 0;


      for(int B = 0; B < arrayA.length; B++)
      {
         if(arrayA[B] != varB)
         {
           index++;
         }
      }
      return arrayX;
   }
}
0

2 Answers 2

1

Simple one liner should suffice:

    public static int[] newSmallerArray( int[] arrayA, int varB)
{
    return Arrays.stream(arrayA).filter(i -> i != varB).toArray();
}
Sign up to request clarification or add additional context in comments.

Comments

0

you missed to initialize array arrayX, try following solution

 public class Harrison7b
  {
   public static void main(String [] args)
   {
    int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
    int varB = 8;
    // Call with the array and variable you need to find.
    int[] result =  newSmallerArray(arrayA, varB);

  for(int x = 0; x < result.length; x++)  {
    System.out.print(result[x] + " ");
   }

 }

  public static int[] newSmallerArray( int[] arrayA, int varB)
   {
  int count = 0;   

  for(int x = 0; x < arrayA.length; x++)
  {
     if(arrayA[x] == varB)
     {
        count++;
     }
  }
     int [] arrayX = new int[arrayA.length - count];

     int index = 0;


  for(int B = 0; B < arrayA.length; B++)
  {
     if(arrayA[B] != varB)
     {
         arrayX[index]= arrayA[B];
       index++;
     }
  }
  return arrayX;
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.