我如何使用epsilon的声明值来检查可容忍值?



我想使用epsilon检查用户输入的权重是否在可容忍范围内容许值可以是小的15.50 - epsilon到15.50 + epsilon,大的25.25 - epsilon到25.25 + epsilon

import java.util.Scanner;
public class ShippedItem {
private int size; 
private double weight; 
public static final int SMALL = 1;
private static final double SMALL_WEIGHT = 9.25; 
public static final int BIG = 2;
private static final double BIG_WEIGHT = 15.75; 
private static final double EPSILON = 0.01;
public ShippedItem() {
this(SMALL, SMALL_WEIGHT);
}

public ShippedItem(int size, double weight) {
this.size = size;
this.weight = weight;
}


public int getSize() {
return size;
}


public void setSize(int size) {
this.size = size;
}


public double getWeight() {
return weight;
}


public void setWeight(double weight) {
this.weight = weight;
}

public boolean isShippedItemAcceptable() {
boolean result = false;

if(size == SMALL) return Math.abs(SMALL_WEIGHT - weight) <= EPSILON;
if (size == SMALL) return Math.abs(SMALL_WEIGHT + weight) <= EPSILON;
else
if(size == BIG) return Math.abs(BIG_WEIGHT - weight) <= EPSILON;
if(size == BIG) return Math.abs(BIG_WEIGHT + weight) <= EPSILON;
return result;
}




public static class User {

private Scanner keyboard = new Scanner(System.in);

public int inputInteger() {
int value = keyboard.nextInt();
keyboard.nextLine();
return value;
}

public int inputInteger(String message) {
System.out.println(message);
int value = inputInteger();
return value;
}


public double inputDouble() {
double value = keyboard.nextDouble();
keyboard.nextLine();
return value;   
}

public double inputDouble(String message) {
System.out.println(message);
double value = inputDouble();
return value;
}


public static void main(String[] args) {
ShippedItem item = new ShippedItem();
User user = new User();

int itemSize;
boolean result;
double itemWeight;
int acceptable = 0;
int unacceptable = 0;
int size = 0;




System.out.println("enter bag size:");
System.out.println("1 for regular");
System.out.println("2 for large");
Scanner keyboard = new Scanner(System.in);
itemSize = keyboard.nextInt();

System.out.println("enter weight:");
itemWeight = keyboard.nextDouble(); 
item.setWeight(itemWeight);
result = item.isShippedItemAcceptable();
System.out.println(result);

System.out.println(item.isShippedItemAcceptable() ? "acceptable" : "unacceptable");
}
}
}

它只适用于小件物品,但对于大件物品,它的输出对于所有重量都是不可接受的

检查重量与尺寸的可接受重量之间的绝对差值是否小于epsilon

if(size == SMALL) return Math.abs(SMALL_WEIGHT - weight) <= EPSILON;
if(size == BIG) return Math.abs(BIG_WEIGHT - weight) <= EPSILON;
return false; // maybe throw Exception for invalid size

最新更新