I have a problem accessing the values in my array for the purpose of subtracting the values held in column 1 of the array from the value I’m trying to get the nearest match to. I’m getting a type mismatch error cannot convert from double to int
As a bit of an aside I’m even sure if I’m approaching the problem in the correct way. I have a table where I check the values in column 1 for the closest value to the one I’m looking for and the other columns in that row are the values that need to be returned. (think a bit like some of the tables in AD&D if you played it)
// Column 1 ability score, 2 Damage mod, 3 Lift , 4 carry, 5 drag
double arr [][] = {{1.01,-7,11,9,28},
{1.51,-6,25,12,63},
{2.01,-6,38,14,96},
{2.51,-5,51,14,96},
{3.01,-5,51,17,128}};
public double EXTcha(double cha) {
double closestNo = 0;
double lookingFor = cha;
int reqIndex = 0;
double i;
for (int row=0; row < arr.length; row++) {
System.out.println(row+"row \t");
double currentDiff = (lookingFor-arr[i][0]);
System.out.println(currentDiff+"diff \t");
if (currentDiff < closestNo) {
closestNo = currentDiff;
System.out.println(closestNo+"closest \t");
reqIndex = row;
};
}
for (int column=0; column<arr[reqIndex].length;column++) {
System.out.println(arr[reqIndex][column]+"\t");
}
return extcha;
}
Here is the code for others after making the suggested changes
// Column 1 ability score, 2 Damage mod, 3 Lift , 4 carry, 5 drag
double arr [][] = {{1.01,-7,11,9,28},
{1.51,-6,25,12,63},
{2.01,-6,38,14,96},
{2.51,-5,51,14,96},
{3.01,-5,51,17,128}};
public double EXTcha(double cha) {
double closestNo = 50;
double lookingFor = cha;
int reqIndex = 0;
for (int row=0; row < arr.length; row++) {
System.out.println(row+"row \t");
double currentDiff = Math.abs(lookingFor-arr[row][0]);
System.out.println(currentDiff+"diff \t");
if (currentDiff < closestNo){
closestNo = currentDiff;
System.out.println(closestNo+"closest \t");
reqIndex = row;
};
}
for (int column=0; column<arr[reqIndex].length;column++) {
System.out.println(arr[reqIndex][column]+"\t");
}
return extcha;
}
I ran into another problem initializing closestNo to 0 meant that when I tested it against (currentDiff < closestNo) it was always less than so I set it to 50 which will always be greater than the double values held in column 1.
I hope this might help someone
There is (at least) one bug in your algorithm, here:
To get the closest match, you should use the absolute value of the difference here. Otherwise you will most likely end up always “matching” the last row (with the highest value), as that will give the smallest negative result within the expression above.
(And, as others switftly mentioned, you should use
ints for indexing into arrays).Overall, your approach is very low-level and brittle. You would better use a
NavigableMapimplementation, such asTreeMap, for this job, with the keys being the first elements in your rows and the values aListcontaining the rest of the numbers in each row, e.g. something like: