我很困惑并坚持如何在数组中找到我的代码的最大值和最小值。我必须使用Integer.MAX_Value和Integer.MIN_Value。
public class AnnualFuelUseTester
{
public static void main(String [] args)
{
int sMiles1, eMiles1, dist;
double price , gallons, mpg, GPM;
int counter = 0;
int total;
AnnualFuelUse[] annual = {new AnnualFuelUse(12700,12751,51,2.8),
new AnnualFuelUse(12802,12908,106,5.8),
new AnnualFuelUse(12908,13014,106,5.8)};
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int index = 0; index < annual.length; index++)
{
annual[index].calcDistance();
annual[index].calcMPG();
annual[index].calcTotal();
}
System.out.println(
"Fill up Start Miles End Miles Distance Gallons Used MPG Price Cost");
for(int index = 0; index < annual.length; index++)
{
System.out.printf(" %d %6d %5d %5d %.2f %.2f %.2f %.2f\n",
index + 1,
annual[index].getStart(),annual[index].getEnd(),
annual[index].getDist(), annual[index].getGal(),
annual[index].getMPG(), annual[index].getPrice(),
annual[index].getTotal());
}
System.out.println("Minimum: " + max);
}
}
这里我的其他课程一起使用
public class AnnualFuelUse
{
private int sMiles1, eMiles1,dist;
private double price, gallons, mpg, total, GPM;
AnnualFuelUse(int s1, int e1, int distance, double gals)
{
sMiles1 = s1;
eMiles1 = e1;
dist = distance;
price = 1.83;
gallons = gals;
}
public void calcDistance()
{
dist = eMiles1 - sMiles1;
}
public double getPrice()
{
return price;
}
public void calcMPG()
{
mpg = dist / gallons;
}
public int getStart()
{
return sMiles1;
}
public int getEnd()
{
return eMiles1;
}
public int getDist()
{
return dist;
}
public double getMPG()
{
return mpg;
}
public double getGal()
{
return gallons;
}
public void calcTotal()
{
total = 1.83 * gallons;
}
public double getTotal()
{
return total;
}
}
我要求简要介绍如何找到最小和最大数组。特别是相同的具体数字(例如51,106是我的距离)
答案 0 :(得分:0)
我担心我必须猜测你希望最小化或最大化的价值。所以它是距离,因为你想使用整数值。
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int index = 0; index < annual.length; index++)
{
annual[index].calcDistance();
if (annual[index].getDist() < min) annual[index].getDist() = min;
if (annual[index].getDist() > max) annual[index].getDist() = max;
annual[index].calcMPG();
annual[index].calcTotal();
....
}
如果使用double值,请注意Double.MIN_VALUE是double可能具有的最高值。你需要-Double.MAX_VALUE。