Wednesday, February 12, 2014

rainApp


Programming Fundamentals
CS1336

Assignment #3 - Basic Calculations Continued

Program #2 - Using a string variable

For the second problem, please implement Problem 4 on page 143 of the text. A scan of the problem is provided below.

This problem asks you to calculate the average rainfall for three months. The program should ask the user to enter the name of each month, such as June or July, and the amount of rain (in inches) that fell each month. The program should then display a message similar to the following:

The average rainfall for June, July, and August was 6.72 inches.

Note that the rainfall average is printed to two decimal places this time.

What is different in this problem is that we are asking the user for string data, and not just numeric input. To accomplish that in a C++ program, we can use the string class. Simply declare three variables of type string to receive the month name input from cin. Don’t forget to include the <string> header file.


package rainApp;
 
import java.util.Scanner;
import java.text.*;
 
public class rainApp {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  DecimalFormat df = new DecimalFormat("0.00");
  double rainfall, avgrainfall;
  double totalrainfall = 0;
 
  System.out.println("This program will find 3 months average rainfall");
 
  System.out.print("Type three months and press enter after each one \nMonth 1: ");
  String monthone = input.nextLine();
  System.out.print("Month 2: ");
  String monthtwo = input.nextLine();
  System.out.print("Month 3: ");
  String monththree = input.nextLine();
 
  System.out.print("How many inches of rain fell for " + monthone + "? ");
  rainfall = input.nextDouble();
  totalrainfall += rainfall;
 
  System.out.print("How many inches of rain fell for " + monthtwo + "? ");
  rainfall = input.nextDouble();
  totalrainfall += rainfall;
 
  System.out.print("How many inches of rain fell for " + monththree+ "? ");
  rainfall = input.nextDouble();
  totalrainfall += rainfall;
 
  avgrainfall = (totalrainfall / 3);
  System.out.print("The average rainfall for months " + monthone + ", "+ monthtwo + ", and " + monththree + " is: "+ (df.format(avgrainfall) + "in"));
 
 }
 
}

No comments:

Post a Comment