Basically I’m trying to make doubles work with integers and maybe I’m missing something obvious, but, with the return highValue code, I’m getting an error that says, “Possible loss of precision, required: int, found: double”. As far as comments are concerned, it’s for a class I’m taking. Here’s the code:
package pj701;
public class PJ70103 {
public static void main(String[] args)
{ //DO NOT CHANGE ANYTHING IN THE MAIN()
double[] x = { 11.11, 66.66, 88.88, 33.33, 55.55 };
double[] y = { 9, 6, 5, 8, 3, 4, 7, 4, 6, 3, 8, 5, 7, 2 };
double[] z = { 123, 400, 765, 102, 345, 678, 234, 789 };
int index = FindIndexHighest (x);
System.out.printf( "%s%5d%s%8.2f\n", "Array x: element index = " , index,
" element contents = ", x[index] );
index = FindIndexHighest (y);
System.out.printf( "%s%5d%s%8.2f\n", "Array y: element index = " , index,
" element contents = ", y[index] );
System.out.printf( "%s%5d%s%8.2f\n", "Array z: element index = ",
FindIndexHighest (z), " element contents = ",
z[FindIndexHighest (z) ] );
}
//======================================================
// put your method definition here - - ONE method
//======================================================
public static int FindIndexHighest(double[] x)
{
double highValue = 0;
for (int i = 1; i < x.length; i++)
{
if (x[i] > highValue)
{
highValue = x[i];
}
else
{
highValue = highValue + 0;
}
}
return highValue;
}
}
I think you need to check the requirements of the assignment again. It’s not the value that’s being asked for, but the index of this value in the passed array.
As for the compiler warning, it means that when you try to implicitly cast a double into an int you may loose some of the information you had. E.g.
double d = 3.5; int i = d;will result ini == 3, so the information after the decimal is lost. This is what the compiler is warning you about. To get rid of the warning, issue an explicit cast, e.g.int i = (int)d;in the above example.