Part of my program tests if two numbers are equal. Because certain operations take only doubles and others take only ints, I am comparing ints and doubles. The programs is returning that the two are equal even when they only round to being equal (i.e. 7.5=7
). I only want the program to return true if the two actually are equal. I've tried the solutions listed here: How to test if a double is an integer
to determine if my doubles are ints.
All of them appear to work - they compile, but the program still returns 7=7.5
I've tried going the other direction also - converting my ints to doubles - same result. How do I get my program to acknowledge the difference? With the most current suggestion:
import acm.program.ConsoleProgram;
import java.awt.Color;
import acm.io.IODialog;
import java.text.*;
import static java.lang.Math.*;
import java.util.*;
/** Tests to see if user color matches sample colors */
public class ColorMatch extends ConsoleProgram
{
//defining sample colors
Color[] dmc =
{
new Color(255,255,255),
new Color(43,57,41),
new Color(213,39,86),
new Color(0,160,130),
new Color(0,0,0),
};
public void run()
{
average();
}
//averages three colors, then tests for match to given color
public void average()
{
//asks for stitch color
IODialog dialog = new IODialog();
int stitchRed = dialog.readInt("Enter red value: ");
int stitchGreen = dialog.readInt("Enter green value: ");
int stitchBlue = dialog.readInt("Enter blue value: ");
Color stitchColor = new Color(stitchRed,stitchGreen,stitchBlue);
//gets averages for dmc colors
for (Color i:dmc)
{
for (Color j:dmc)
{
for (Color k:dmc)
{
int indexI = Arrays.asList(dmc).indexOf(i);
int indexJ = Arrays.asList(dmc).indexOf(j);
int indexK = Arrays.asList(dmc).indexOf(k);
if (indexI <= indexJ && indexJ <= indexK)
{
int iRed = i.getRed();
int jRed = j.getRed();
int kRed = k.getRed();
int iGreen = i.getGreen();
int jGreen = j.getGreen();
int kGreen = k.getGreen();
int iBlue = i.getBlue();
int jBlue = j.getBlue();
int kBlue = k.getBlue();
double redAverage = (iRed+jRed+kRed)/3;
double greenAverage = (iGreen+jGreen+kGreen)/3;
double blueAverage = (iBlue+jBlue+kBlue)/3;
if (redAverage == (int)redAverage && greenAverage == (int)greenAverage && blueAverage == (int)blueAverage)
{
int rAverage = (int)redAverage;
int gAverage = (int)greenAverage;
int bAverage = (int)blueAverage;
Color colorAverage = new Color(rAverage,gAverage,bAverage);
//tests to see if any average equals the stitch color
if (colorAverage.equals(stitchColor))
{
println("The color match is: " + i + ", " + j + ", " + k);
}
}
}
}
}
}
I plugged in 85s as my test numbers.
The only result should be (0,0,0)+(0,0,0)+(255,255,255)
, but it is also yielding (43,57,41)+(213,39,86)+(0,160,130) . (41+86+130)/3=85.7!=85
.