Saturday, December 6, 2014

How to find how many times a number appears in an array.




Please help me, this is my code up to now and I can't do anything to make it work. I want it to tell me how many times the number 3 appears, and the last position it was in. I have tried everything and I am ready to give up.




I am getting errors like"Cuanto.java:88: getPosition(double[],double) in Cuanto cannot be applied to (double)



a = getPosition(a);" and unreachable statements, and value not found. It's all over the place every time I make a change to it.






Java Code:






public class Cuanto {

static int getPosition(int count,double listOfValues[],

double targetValue)

{
int a = 0, i;
for (i=0; i < listOfValues.length; i++)
{
if (listOfValues[i] == targetValue)
{
a++;
}
}
return a;
}


static int getPosition(double listOfValues[],

double targetValue)
{
int i,a = 0,

position = -1;

for (i=0; i < listOfValues.length; i++)
{




if (listOfValues[i] == targetValue)


{

position = i;
a = a + 1;

}
}

return position;



}




static int getPosition2(double listOfValues[],

double targetValue )

{
int i,

position = -1;

boolean found = false;


for (i=0; (i < listOfValues.length) && (!found); i++)

{



if (listOfValues[i] == targetValue)


{


position = i;

found = true;

}

}



return position;


}


public static void main(String[] args)

{


double list[] = {1,6,3,8,5,8,3,4,8,3};


int position,
a = 0;


position = getPosition(list, 3);



if (position != -1)

{


System.out.println("Value found at position "

+ position + "\n\n" + "And is found " + a + " times");

}

else

{


System.out.println("Value not found \n\n");

}

position = getPosition2(list, 3);


if (position != -1)

{


System.out.println("Value found at position "

+ position + "\n\n");



}
else
{


System.out.println("Value not found \n\n");

}
}
}







No comments:

Post a Comment