sprakera sprakera - 9 days ago 6
Java Question

Java return (value) error

I have tried different things with this code, but always get different errors.

The instructions for the program is that I need to have a function (besides from main) that receives arguments for an array of integer values and a second argument telling the desire value to look in the array by the user. Also it must return how many times the desire value is repeated on the array.

The errors are related with the counter and in the main function. I think I am not returning the counter value correctly.

This is the code I have for now:

import java.util.Scanner;
import java.util.Arrays;

public class ArregloBusqueda2
{
static int findRepetition(int listOfValues[], int targetValue, int counter)
{
int i;
boolean found = false;

for(i=0; i<listOfValues.length; i++)
{
while((counter < listOfValues.length))
{
if(listOfValues[i] == targetValue)
{
counter = counter + 1;
}
}
}
return counter;
}


public static int main(String[] args)
{
Scanner input = new Scanner (System.in);

int targetValue;
int listOfValues[] = {1,6,3,8,5,8,3,4,8,3};

System.out.println("Please enter the desire number to look for: ");
targetValue=input.nextInt();

findRepetition(targetValue, counter);


if(counter != 0)
{
System.out.println("The frequency of the number " + targetValue + " is: " + counter);
}
else
{
System.out.println ("The number " + targetValue + " is not contained in the array list");
}
}
}

Answer

Multiple issues in your code.

  1. public static int main(String[] args) should be public static void main(String[] args)
  2. findRepetition takes three arguments, but you are passing two agruments
  3. counter variable is not declared
  4. Logical flaw, while((counter < listOfValues.length)) will keep on executing if counter value is less than listOfValues.

     static int findRepetition(int listOfValues[], int targetValue) {
        int i;
        int counter = 0;
    
        for (i = 0; i < listOfValues.length; i++) {
            if (listOfValues[i] == targetValue) {
                counter = counter + 1;
            }
        }
        return counter;
    }
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
    
        int targetValue;
        int listOfValues[] = { 1, 6, 3, 8, 5, 8, 3, 4, 8, 3 };
    
        System.out.println("Please enter the desire number to look for: ");
        targetValue = input.nextInt();
    
        int counter = findRepetition(listOfValues, targetValue);
    
        if (counter != 0) {
            System.out.println("The frequency of the number " + targetValue + " is: " + counter);
        } else {
            System.out.println("The number " + targetValue + " is not contained     in the array list");
        }
    
    }
    
Comments