Java "Fat Gram Calculator" programming I'm attempting needs to validate input, I get to a point where I need to validate the input from user, taking into consideration a previous input from another module, with a given formula. I am trying this and I don't know how to do that without asking the user to input the same thing again, please help the problem is on this line:
while(input < 0.0 || input < (fatGrams * 9)){
in the code below
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.");
}
}
}
You need to pass the fatGrams variable as an argument to the getCalories() method, like this:
// Calls getFat
fatGrams = getFat();
// Calls getCalories
calories = getCalories(fatGrams);
// Calls showPercent
showPercent(fatGrams, calories);
}
And change the signature of your getCalories() method like this:
public static double getCalories(double fatGrams) {
Scanner keyboard = new Scanner(System.in);
Now the class can compile and the following line doesn't have any problem anymore:
// Validate
while (input < 0.0 || input < (fatGrams * 9)) { // <<<<<< NO MORE PROBLEM !
Hope it helps.