简体   繁体   中英

Type mismatch: cannot convert from double [] to int []

I am trying to have the method return the new array that was made by the for loop.

import java.util.Arrays;
public class stocks {

public static void main(String[] args) {

    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2}; 
    double isOverprices [] = overpriced(stockV);

}
    public int [] overpriced(double[] rsiValues)
    {
        for (int i = 0; i < rsiValues.length; i++)
        {
            if (rsiValues[i] > 70)
            {
                rsiValues[i] = 1;
            }
            else if (rsiValues[i] <= 70)
            {
                rsiValues[i] = 0;
            }
            return rsiValues;
        }
    }
 }

Change to

public double[] overpriced(double[] rsiValues)

You are obviously returning what you pass into the method, so why do you think its kind will change?

Also, you want to return the values after the for loop has ended.

for (int i = 0; i < rsiValues.length; i++)
{
    if (rsiValues[i] > 70)
    {
        rsiValues[i] = 1;
    }
    else if (rsiValues[i] <= 70)
    {
        rsiValues[i] = 0;
    }

}
return rsiValues;
  1. Add 'static' to the overpriced method signature.
  2. The overpriced method should return an array of ints but you're returning an array of doubles.
  3. Put your return statement outside of the for loop.
  4. In the main method, change isOverprices to an int array
  public static void main(String[] args) {
    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2}; 
    int isOverprices [] = overpriced(stockV);
    for(int i: isOverprices) {
      System.out.println(i);
    }
  }
  public static int [] overpriced(double[] rsiValues){
    int result [] = new int[rsiValues.length];
    for (int i = 0; i < rsiValues.length; i++)
    {
      if (rsiValues[i] > 70)
      {
          result[i] = 1;
      }
      else if (rsiValues[i] <= 70)
      {
          result[i] = 0;
      }
    }
    return result;
  }

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