Given the following was entered from the keyboard: 1 you displayed: Enter number
ID: 3879693 • Letter: G
Question
Given the following was entered from the keyboard:
1
you displayed:
Enter number of cookies eaten:Your calorie intake was: 75 calories
So where is my java error in the following:
import java.util.Scanner;
/**
* @author
*
*/
public class CookieCalorieCounter {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
// prompt read the number of cookies eaten
System.out.print("Enter number of cookies eaten:");
int cookieCount = scanner.nextInt();
int servingSize = 40 / 10;
int caloriesPerCookie = 300 / servingSize;
int totalCalories = cookieCount * caloriesPerCookie;
// print the result console
System.out.println("Your calorie intake was: " + totalCalories
+ " calories");
} catch (Exception e) {
// TODO: handle exception
} finally {
if (scanner != null) {
scanner.close();
}
}
}
}
instead of:
Enter number of cookies eaten: Your calorie intake was: 75 calories.
Explanation / Answer
Note : The code is working fine.Here ,We no need to write the code inside the try catch block.Bec these is no chance of getting exception during runtime.As we are not accessing any files,no chance of divided by zero etc.
But I didnt understand why you declared
int servingSize = 40 / 10;
int caloriesPerCookie = 300 / servingSize;
Bec,anyway the caloriesPerCookie is 75.
__________
CookieCalorieCounter.java
import java.util.Scanner;
/**
* @author
*
*/
public class CookieCalorieCounter {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// prompt read the number of cookies eaten
System.out.print("Enter number of cookies eaten:");
int cookieCount = scanner.nextInt();
int servingSize = 40 / 10;
int caloriesPerCookie = 300 / servingSize;
int totalCalories = cookieCount * caloriesPerCookie;
// print the result console
System.out.println("Your calorie intake was: " + totalCalories
+ " calories");
scanner.close();
}
}
________________
Output:
Enter number of cookies eaten:5
Your calorie intake was: 375 calories
_______________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.