-1

having a problem with my java program. I am a newbie to Java and just can't figure out what is exactly the issue with it. In short I've declared an array and a variable in main, I've created my method call and would like my array be passed into my method with the variable. I would then like the method to take my array and count the number of times my variable "8" occurs, get rid of the 8 out of the array and return a new smaller array back to main. Here is my code below. I feel as if I am just missing one block code any suggestions?

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];




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

         }
      }
      return arrayX;
   }
}
Clark1776
  • 1
  • 2

2 Answers2

0

you do not actually need to return the array because when you pass an array to a method you also pass its memory address meaning its the same address that you change so, it will also change the arraysA of main method because you are just changing the values of the same memory adress

import java.util.*;




public class Help
{


public static void main(String[] args)
{
    ArrayList<Integer> arraysA = new ArrayList<Integer>();
    arraysA.add(Integer.valueOf(2));
    arraysA.add(Integer.valueOf(4));
    arraysA.add(Integer.valueOf(8));
    arraysA.add(Integer.valueOf(19));
    arraysA.add(Integer.valueOf(32));
    arraysA.add(Integer.valueOf(17));
    arraysA.add(Integer.valueOf(17));
    arraysA.add(Integer.valueOf(18));
    arraysA.add(Integer.valueOf(25));
    arraysA.add(Integer.valueOf(17));
    arraysA.add(Integer.valueOf(8));
    arraysA.add(Integer.valueOf(3));
    arraysA.add(Integer.valueOf(4));
    arraysA.add(Integer.valueOf(8));
     int varB=8;
    newSmallerArray(arraysA,varB);
    for(Integer i:arraysA)
    {
        System.out.println(i);
    }


}
public static void newSmallerArray(ArrayList<Integer> arraysA,int varB)
{
    for(int i=0;i<arraysA.size();++i)
    {
        if(Integer.valueOf(arraysA.get(i))==varB)
        {
            arraysA.remove(i);
        }
    }
}

}

0xDEADBEEF
  • 590
  • 1
  • 5
  • 16
0

Try this code it will not require for loop:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(arrayA));
list.removeAll(Arrays.asList(8));
arrayA = list.toArray(array);
Fady Saad
  • 1,169
  • 8
  • 13