简体   繁体   中英

Type Incompatibility

I'm trying to create a method that returns the mode of an array (I'm not asking how to make the method and would rather you not give me any ideas. For those of you who keep criticizing my questions for being repeats of others, I know that the answer is already on this website. That's not the question). I made a method, in a class called BasicMathMethods, called getTotal:

public static int getTotal(double[] a, int b)
{
    int count = 0;
    int Element;
    for(Element = 0; Element < a.length; Element++)
    {
        if(a[b] == a[Element])
        {
            count++;
        }
    }
    return count;
}

And I tried to use this method in my mode method:

 public static double Mode(double[] a)
{
    for(int element = 0; element < a.length; element++)
    {
        int[] largest = BasicMathMethods.getTotal(a, element);// gets the count of each element
        Arrays.sort(largest);
        if(BasicMathMethods.getTotal(a, element) == largest.length)
        return a[element];
    }
}

However, my compiler (which is Blue J by the way) says "Incompatible types: int cannot be converted to int[]", and highlights (a, element). I don't understand the error. I don't see where I am trying to convert int[] to int. Could anyone tell me what the error is and explain?

You return an int from getTotal and are trying to put it into an int[] variable.

int[] largest = BasicMathMethods.getTotal(a, element);

The return type of getTotal is int

public static int getTotal(double[] a, int b)

If you want to add the value you get from BasicMathMethods.getTotal(a, element) to an array, there are a few complications. You don't know how many values you will get. Therefore, you will not be able to know the required size of the array.

Use an ArrayList instead of an array.

But more importantly. I would like to point out major issues with your approach to obtain the mode . Read over the code below to see if it makes sense.

public static double mode(double[] a) {

    double currentBestCandidate = a[0];
    int countCurrentBestCandidate = BasicMathMethods.getTotal(a, 0);

    // we already have index 0, lets start from 1
    for(int element = 1; element < a.length; element++) {
        int count = BasicMathMethods.getTotal(a, element);

        // if this count is greater than what we have 
        // right now, we need to update currentBestCandidate 
        // and countCurrentBestCandidate
        if(count > countCurrentBestCandidate) {
            currentBestCandidate = a[element];
            countCurrentBestCandidate = count;
        }
    }
    return currentBestCandidate;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM