error: incompatible types: possible lossy conversion from double to int

匿名 (未验证) 提交于 2019-12-03 01:44:01

问题:

public class FoodItem {   private String name;  private int calories;  private int fatGrams;  private int caloriesFromFat;   public FoodItem(String n, int cal, int fat) {     name = n;     calories = cal;     fatGrams = fat;    }   public void setName(String n) {     name = n;  }   public void setCalories(int cal) {     calories = cal;   }   public void setFatGrams(int fat) {     fatGrams = fat;    }   public String getName() {     return name;  }   public int getCalories() {     return calories;  }   public int getFatGrams() {     return fatGrams;   }   public int getCaloriesFromFat() {     return (fatGrams * 9.0);   }   public int getPercentFat() {     return (caloriesFromFat / calories);  }   // Ignore for now  public String toString() {     return name + calories + fatGrams;  } } 

My instructions are to "Include a method named caloriesFromFat which returns an integer with the number of calories that fat contributes to the total calories (fat grams * 9.0).", but when I try to compile I get the above error. I have no clue what I have wrong.

回答1:

You've used a double literal 9.0 in your multiplication in getCaloriesFromFat. Because of this, fatGrams is promoted to a double for the multiplication, and the product is a double. However, you have that method returning an int.

You can use an int literal (9, no decimal point) or you can have getCaloriesFromFat return a double instead of an int. Since you're just multiplying by 9, I would use the int literal 9.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!