SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Flow Of Control
Exercise:
Programming Projects
Question:12 | ISBN:9780132830317 | Edition: 5

Question

Redo or do for the first time Programming Project 2.13 from Chapter 2 but this time use a loop to read the names from the file. Your program should also handle an arbitrary number of entries in the file instead of handling only three entries. To do this, your program must check to see if there is still data left to read (i.e., it has reached the end of the file). The appropriate methods to read from a file are described in Section 2.3.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Review1 {
    public static final int WEIGHT_FOR_MINIMUM_HEIGHT_IN_POUNDS = 110;
    public static final int MINIMUM_ALLOW_HEIGHT_IN_FEET = 5;
    public static final int WEIGHT_PER_ADDITIONAL_INCH_IN_POUNDS = 5;
    public static final int INCHES_PER_FEET = 12;
    public static void main(String[] args) {
        Scanner fileIn = null;
        try {
            fileIn = new Scanner(new FileInputStream("file.txt"));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("File not found.");
            System.exit(0);
        }
    
        double idealBodyWeight;
        for (int i=1; fileIn.hasNext(); i++)
        {
            String name = fileIn.nextLine();
            double heightFeet = fileIn.nextDouble();
            double heightInche = fileIn.nextDouble();
            fileIn.nextLine();
            idealBodyWeight = WEIGHT_FOR_MINIMUM_HEIGHT_IN_POUNDS + ((heightFeet - MINIMUM_ALLOW_HEIGHT_IN_FEET)*INCHES_PER_FEET 
                    + heightInche)*WEIGHT_PER_ADDITIONAL_INCH_IN_POUNDS;
            
            
            System.out.println(i + "-" + "\"" + name + "\"" + " ideal body weight is: " + idealBodyWeight + " Pounds.");
            
            
        } 
        
        fileIn.close();
        
    }    
    
    
}
 

0 0

Discussions

Post the discussion to improve the above solution.