Java“脂肪克计算器”编程我试图需要验证输入,我得到了一个点,我需要验证用户的输入,考虑到以前的输入从另一个模块,与给定的公式.我正在尝试这一点,我不知道如何做到这一点,而不要求用户输入同样的事情了,请帮助问题是在这一行:
while(input < 0.0 || input < (fatGrams * 9)){
在下面的代码中
import java.util.Scanner;
class fatCalculator {
public static void main(String[] args) {
// Local variables
double fatGrams, calories;
// Calls getFat
fatGrams = getFat();
// Calls getCalories
calories = getCalories();
// Calls showPercent
showPercent(fatGrams, calories);
}
public static double getFat() {
Scanner keyboard = new Scanner(System.in);
// Local variable
double input;
// Get the fat grams
System.out.println("Please enter the number of fat grams: ");
input = keyboard.nextDouble();
// Valitdate
while (input < 0.0) {
System.out.println("The number of fat grams cannot be less than 0.");
System.out.println("Please enter the number of fat grams.");
input = keyboard.nextDouble();
}
return input;
}
public static double getCalories() {
Scanner keyboard = new Scanner(System.in);
// Local variable
double input;
// call fatGrams
// Get the calories
System.out.println("Please enter the number of calories: ");
input = keyboard.nextDouble();
// Validate
while (input < 0.0 || input < (fatGrams * 9)) { // <<<<<< PROBLEM IS HERE
System.out.println("The number of calories cannot be less than the number of fat grams * 9.");
System.out.println("Please enter the number of calories.");
input = keyboard.nextDouble();
}
return input;
}
public static void showPercent(double fatGrams, double calories) {
// local varibale
double finalPercentage;
// Calculate and display final percentage
finalPercentage = (fatGrams * 9) / calories;
System.out.println("The percentage of calories from fat is " + finalPercentage);
// Banner
while (finalPercentage < 0.3) {
System.out.println("That food item is considered" + "low fat.");
}
}
}
1条答案
按热度按时间vwkv1x7d1#
你需要将fatGrams变量作为参数传递给getCalories()方法,如下所示:
然后像这样更改getCalories()方法的签名:
现在,类可以编译了,下面的行不再有任何问题:
希望有帮助。