Home » Java » java – Type mismatch: cannot convert from double [] to int []-Exceptionshub

java – Type mismatch: cannot convert from double [] to int []-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

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;
        }
    }
 }
How to&Answers:

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;

Answer:

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