我正尝试从每40公斤中减去2公斤的重量。如果我有200Kg,则扣除额将为10kg,依此类推...问题是我每40kg使用IF,请参见编码。请帮助我尽可能地简化此代码。
public void onClick(View view) {
String s = edW.getText().toString();
Float w= Float.parseFloat(s);
Float weight = w*40;
if (weight <= 20){
Float oneKG = weight - 1;
txtV.setText("Total KGs: "+ oneKG);
}
if (weight>20 && weight <=40){
Float twoKG = weight - 2;
txtV.setText("Total KGs: "+ twoKG);
}
if (weight>40 && weight <=80){
Float fourKG = weight - 4;
txtV.setText("Total KGs: "+ fourKG);
}
if (weight>80 && weight <=120){
Float sixKG = weight - 6;
txtV.setText("Total KGs: "+ sixKG);
}
if (weight>120 && weight <=160){
Float eightKG = weight - 8;
txtV.setText("Total KGs: "+ eightKG);
}
if (weight>160 && weight <=200){
Float tenKG = weight - 10;
txtV.setText("Total KGs: "+ tenKG);
}
else {
txtV.setText("Else Running");
}
}
答案 0 :(得分:0)
尝试以下代码,应该可以解决您的问题
class Value{
public int wholeNumber;
public int decimalNumber;
}
private Value getWholeDecimalNumber(String s) {
String[] arr = String.valueOf(s).split("\\.");
Value value = new Value();
value.wholeNumber = Integer.parseInt(arr[0]);
if (arr.length > 1) {
value.decimalNumber = Integer.parseInt(arr[1]);
}
return value;
}
public void onClick(View view) {
String s = edW.getText().toString();
Value value = getWholeDecimalNumber(s);
int w= value.wholeNumber;
int weight = w*40 + value.decimalNumber;
int weightToDeduct = w*2;
if (value.decimalNumber > 0) {
if (value.decimalNumber > 20) {
weightToDeduct += 2;
}
else {
weightToDeduct += 1;
}
}
txtV.setText("Total KGs: "+ (weight - weightToDeduct));
}
例如- a)对于1作为输入,重量= 1x40 = 40,weightToDeduct = 1x2 = 2,总千克=(重量-weightToDeduct)= 40-2 = 38kg
b)输入5时,重量= 5x40 = 200,weightToDeduct = 5x2 = 10,总计kg =(重量-weightToDeduct)= 200-10 = 190kg
答案 1 :(得分:-1)
您还可以尝试将权重除以20:)
答案 2 :(得分:-1)
除以40:
$$prods
注意:当答案的权重完全等于40的倍数时,此答案的较早版本出现一个错误的错误。
如果您真的不希望它超过200,则可以在计算public void onClick(View view) {
String s = edW.getText().toString();
float weight = 40 * Float.parseFloat(s);
if (weight <= 20) {
txtV.setText("Total KGs: " + (weight - 1));
} else {
int forties = (int) Math.ceil(weight / 40f);
txtV.setText("Total KGs: " + (weight - (forties * 2)));
}
}
之后但在完成其余工作之前将其添加:
float weight
它提供了与原始内容相同的语义。