USING JAVA AND USE SCANNER TO READ FROM THE FILE. Calorie intake data from a per
ID: 3884837 • Letter: U
Question
USING JAVA AND USE SCANNER TO READ FROM THE FILE. Calorie intake data from a person is provided in a text file named food.txt. There are arbitrary number of double values on each line, separated by spaces. The numbers represent the number of calories consumed for meals and/or snacks on a day. The file includes data for exactly one week starting from Monday. That is, the file contains seven lines of text. The topmost line is for Monday and the line at the bottom is for Sunday. Your program should read the data from the file into a 2- dimensional array. The number of rows of the 2-dimensional array must be equal to the number of valid lines in the file. The numbers in the i-th row of the 2-dimensional array must appear in the same sequence of numbers in the i-th row of the file. After reading the input file into the 2-dimensional array, report the following items. WRITE A METHOD FOR EACH OF THESE THREE ITEMS 1. LIST OF TOTAL CALORIES CONSUMED EACH DAY 2. LIST OF DAYS WHEN MORE THAN 2250 CALORIES WERE CONSUMED 3. AVERAGE CALORIES CONSUMED DURING THE I-TH MEAL/SNACK(AVERAGE OVER ALL SEVEN DAYS) You should print an error message and terminate if there are not exactly 7 lines.
Explanation / Answer
import java.io.*;
import java.util.*;
public class DemoCalorie {
public static void main(String[] args){
try {
FileInputStream fin = new FileInputStream("food.txt");
Scanner sc = new Scanner(fin);
Scanner sc1 = new Scanner(System.in);
double data[][] = new double[7][2];
int count = 0;
while (sc.hasNext()){
data[count][0] = sc.nextDouble();
data[count][1] = sc.nextDouble();
count++;
}
if (count != 7) {
System.out.println("There is error in input file");
}
else {
for (int i = 0; i<7; i++){
System.out.println("Calories Consumed for day " + (i+1) + " :" + (data[i][0] + data[i][1]));
}
System.out.println("Days on which calories consumed is > 2250:");
for (int i = 0; i<7; i++){
if (data[i][0] + data[i][1] > 2250)
System.out.println("Day " + i);
}
System.out.println("Enter upto which day, average is required :");
int day = sc1.nextInt();
double sum = 0;
for (int i = 0; i<day; i++){
sum = sum + data[i][0] + data[i][1];
}
System.out.println("Average upto " + day + ":" + sum/day);
sum = 0;
for (int i = 0; i<day; i++){
sum = sum + data[i][0] + data[i][1];
}
System.out.println("Average for 7 days:" + sum/7);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.