Wednesday, 6 April 2016

Chapter 2 Exercise 14, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Health application: computing BMI) Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters.


import java.util.Scanner;
 
public class ProgrammingEx2_14 {
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter weight in pounds:");
  double weight = input.nextDouble();
  System.out.print("Enter height in inches:");
  double height = input.nextDouble();
  double BMI = (weight * 0.45359237) / Math.pow(height * 0.0254, 2);
 
  System.out.print("BMI is " + BMI);
 
 }
}

Chapter 2 Exercise 13, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Financial application: compound value) Suppose you save $100 each month into a savings account with the annual interest rate 5%. Thus, the monthly interest rate is 0.05/12 = 0.00417. After the first month, the value in the account becomes 100 * (1 + 0.00417) = 100.417 After the second month, the value in the account becomes (100 + 100.417) * (1 + 0.00417) = 201.252 After the third month, the value in the account becomes (100 + 201.252) * (1 + 0.00417) = 302.507 and so on. Write a program that prompts the user to enter a monthly saving amount and displays the account value after the sixth month. (In Exercise 5.30, you will use a loop to simplify the code and display the account value for any month.)


import java.util.Scanner;
 
public class ProgramEx2_13 {
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter the monthly saving amount:");
  double ini = input.nextDouble();
  double accum = 0;
  accum = (ini + accum) * 1.00417;
  accum = (ini + accum) * 1.00417;
  accum = (ini + accum) * 1.00417;
  accum = (ini + accum) * 1.00417;
  accum = (ini + accum) * 1.00417;
  accum = (ini + accum) * 1.00417;
 
  System.out
    .print("After the sixth month, the account value is " + accum);
 
 }
}

Chapter 2 Exercise 12, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Physics: finding runway length) Given an airplane’s acceleration a and take-off speed v, you can compute the minimum runway length needed for an airplane to take off using the following formula: length = v^2/2a Write a program that prompts the user to enter v in meters/second (m/s) and the acceleration a in meters/second squared (m/s2 ), and displays the minimum runway length.



import java.util.Scanner;
 
public class ProgrammingEX2_12 {
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter speed and acceleration:");
  double v = input.nextDouble();
  double a = input.nextDouble();
  double length = Math.pow(v, 2)/(2*a);
   
  System.out.print("The minimum runway length for this airplane is " + length);
 
 }
}

Chapter 2 Exercise 11, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Population projection) Rewrite Programming Exercise 1.11 to prompt the user to enter the number of years and displays the population after the number of years. Use the hint in Programming Exercise 1.11 for this program. The population should be cast into an integer.


import java.util.Scanner;
 
public class ProgrammingEx2_11 {
 
 public static void main(String[] args) {
  long newPop = 0, current = 312032486;
  int time;
  int birth, death, immigrant;
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter the number of years:");
  int v = input.nextInt();
 
  for (int i = 1; i <= v; i++) {
   // Convert time to second
   time = i * 365 * 24 * 60 * 60;
   // Calculating population increase/decrease in each case
   birth = time / 7;
   death = time / 13;
   immigrant = time / 45;
   // calculate new population
   newPop = current + birth - death + immigrant;
 
  }
 
  System.out.println("The population in " + v + "years is " + newPop);
 }
 
}

Chapter 2 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Science: calculating energy) Write a program that calculates the energy needed to heat water from an initial temperature to a final temperature. Your program should prompt the user to enter the amount of water in kilograms and the initial and final temperatures of the water. The formula to compute the energy is Q = M * (finalTemperature – initialTemperature) * 4184 where M is the weight of water in kilograms, temperatures are in degrees Celsius, and energy Q is measured in joules



import java.util.Scanner;
 
public class ProgrammingEx2_10 {
 
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter the amount of water in kilograms:");
  double M = input.nextDouble();
  System.out.print("Enter the initial temperature:");
  double initialTemperature = input.nextDouble();
  System.out.print("Enter the final temperature:");
  double finalTemperature = input.nextDouble();
 
  double Q = M * (finalTemperature - initialTemperature) * 4184;
  System.out.print("The energy needed is " + Q);
 
 }
}

Friday, 1 April 2016

Chapter 2 Exercise 9, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

2.9 (Physics: acceleration) Average acceleration is defined as the change of velocity divided by the time taken to make the change, as shown in the following formula: `a = (v1 - v0)/t` Write a program that prompts the user to enter the starting velocity v0 in meters/ second, the ending velocity v1 in meters/second, and the time span t in seconds, and displays the average acceleration.


import java.util.Scanner;
public class Exersice_09 {
public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter v0, v1, and t:");
  double v0 = input.nextDouble();
  double v1 = input.nextDouble();
  double t = input.nextDouble();
  double avg = (v1 - v0) / t;
 
  System.out.println("The average acceleration is " + avg);
 
 }
 
}

Chapter 2 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

2.8 (Current time) Listing 2.7, ShowCurrentTime.java, gives a program that displays the current time in GMT. Revise the program so that it prompts the user to enter the time zone offset to GMT and displays the time in the specified time zone



import java.util.Scanner;
public class Exersice_08 {
public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
  System.out.print("Enter the time zone offset to GMT:");
  int offset = input.nextInt();
  // calculate offset in seconds
  offset = offset * 60 * 60;
 
  // Obtain the total milliseconds since midnight, Jan 1, 1970
  long totalMilliseconds = System.currentTimeMillis();
 
  // Obtain the total seconds since midnight, Jan 1, 1970 and apply the offset
  long totalSeconds = (totalMilliseconds / 1000) + offset;
 
  // Compute the current second in the minute in the hour
  long currentSecond = totalSeconds % 60;
 
  // Obtain the total minutes
  long totalMinutes = totalSeconds / 60;
 
  // Compute the current minute in the hour
  long currentMinute = totalMinutes % 60;
 
  // Obtain the total hours
  long totalHours = totalMinutes / 60;
 
  // Compute the current hour
  long currentHour = totalHours % 24;
 
  // Display results
  System.out.println("Current time is " + currentHour + ":"
    + currentMinute + ":" + currentSecond );
 }
}

Chapter 2 Exercise 7, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Find the number of years) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the min- utes. For simplicity, assume a year has 365 days.


import java.util.Scanner;
public class Exersice_07 {
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter the number of minutes:");
  int number = input.nextInt();
  int days = number/(24*60);
  int years = days/365;
 
 
  System.out.println(number + " minutes is approximately " + years +" years and " + days%365 +" days");
 
 }
 
}

Chapter 2 Exercise 6, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Sum the digits in an integer) Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14.
Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93.


import java.util.Scanner;
public class Exersice_06 {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter an integer between 0 and 1000: ");
        int number = input.nextInt();

        int firstDigit = number % 10;
        int remainingNumber = number / 10;
        int SecondDigit = remainingNumber % 10;
        remainingNumber = remainingNumber / 10;
        int thirdDigit = remainingNumber % 10;

        int sum = thirdDigit + SecondDigit + firstDigit;

        System.out.println("The sum of all digits in " + number + " is " + sum);

    }
}

Chapter 2 Exercise 5, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Financial application: calculate tips) Write a program that reads the subtotal and the gratuity rate, then computes the gratuity and total. For example, if the user enters 10 for subtotal and 15% for gratuity rate, the program displays $1.5 as gratuity and $11.5 as total.



import java.util.Scanner;
public class Exersice_05 {

    public static void main(String[] Strings) {

        double gratuityRate,
                gratuityTotal,
                total,
                subtotal;

        Scanner input = new Scanner(System.in);

        System.out.print("Please enter the subtotal and gratuity rate: ");
        subtotal = input.nextDouble();
        gratuityRate = input.nextDouble();

        gratuityTotal = subtotal * gratuityRate * .01;
        total = subtotal + gratuityTotal;

        System.out.print("The gratuity is $" + gratuityTotal + " and total is $" + total);

    }
}

Chapter 2 Exercise 4, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Convert pounds into kilograms) Write a program that converts pounds into kilograms. The program prompts the user to enter a number in pounds, converts it to kilograms, and displays the result. One pound is 0.454 kilograms.

import java.util.Scanner;
public class Exercise_04 {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number in pounds: ");

        double pounds = input.nextDouble();
        double kilograms = pounds * 0.454;

        System.out.println(pounds + " pounds is " + kilograms + " kilograms.");
    }
}

Chapter 2 Exercise 3, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Convert feet into meters) Write a program that reads a number in feet, converts itto meters, and displays the result. One foot is 0.305 meter.

import java.util.Scanner;
public class Exercise_03 {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter a value for feet: ");
        double feet = input.nextDouble();
        double meters = feet * 0.305;
        System.out.println(feet + " feet is " + meters + " meters");

    }
}

Chapter 2 Exercise 2, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Compute the volume of a cylinder) Write a program that reads in the radius and length of a cylinder and computes the area and volume using the following formulas:



import java.util.Scanner;
public class Exercise_02 {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter the radius and the length of a cylinder: ");
        double radius = input.nextDouble();
        double length = input.nextDouble();

        double area = radius * radius * 3.14159265359;
        double volume = area * length;

        System.out.println("The area is " + area);
        System.out.println("The volume is " + volume);
    }
}

Chapter 2 Exercise 1, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Convert Celsius to Fahrenheit) Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows:
fahrenheit = (9 / 5) * celsius + 32
Hint: In Java, 9 / 5 is 1, but 9.0 / 5 is 1.8.


import java.util.Scanner;
public class Exercise_01 {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter a degree in Celsius: ");
        double celsius = input.nextDouble();

        double fahrenheit = (9.0 / 5.0) * celsius + 32.0;
        System.out.println(celsius + " degree Celsius is equal to " + fahrenheit + " in Fahrenheit");
    }
}

Chapter 1 Exercise 13, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Algebra: solve 2 * 2 linear equations) You can use Cramer’s rule to solve the following 2 * 2 system of linear equation:
Write a program that solves the following equation and displays the value for x and y:
3.4x + 50.2y = 44.5
3.4x + 50.2y = 44.5

public class Exercise_13 {

    public static void main(String[] args) {

        // Variables for Cramer's formula
        double a = 3.4;
        double b = 50.2;
        double c = 2.1;
        double d = 0.55;
        double e = 44.5;
        double f = 5.9;

        double x = (e * d - b * f) / (a * d - b * c);
        double y = (a * f - e * c) / (a * d - b * c);

        System.out.println("x = " + x + " y = " + y);

    }
}

Chapter 1 Exercise 12, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Average speed in kilometers) Assume a runner runs 24 miles in 1 hour, 40  minutes, and 35 seconds. Write a program that displays the average speed in kilometers per hour. (Note that 1 mile is 1.6 kilometers.)


public class Exercise_12 {

    public static void main(String[] strings) {

        // Making variables to hold current time and distance
        double hours = 1;
        double minutes = 40;
        double seconds = 35;
        double distanceInMiles = 24;

        // Converting from miles to kilometers
        // Note: the book said 1.6, however 1.60934 is more accurate
        double distanceInKilometers = distanceInMiles * 1.60934;

        // Converting current time (hour, minutes, seconds) into total amount of minutes
        double timeInMinutes = hours * 60.0 + minutes + seconds / 60.0;

        // Calculating kilometers per hour
        // kph = 60 * distance traveled / minutes taken
        double kilometersPerHour = 60.0 * distanceInKilometers / timeInMinutes;

        System.out.println(kilometersPerHour);

    }
}

Chapter 1 Exercise 11, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Population projection) The U.S. Census Bureau projects population based on the following assumptions:
 ■ One birth every 7 seconds
 ■ One death every 13 seconds
 ■ One new immigrant every 45 seconds
 Write a program to display the population for each of the next five years. Assume the current population is 312,032,486 and one year has 365 days. Hint: In Java, if two integers perform division, the result is an integer. The fractional part is truncated. For example, 5 / 4 is 1 (not 1.25) and 10 / 4 is 2 (not 2.5). To get an accurate result with the fractional part, one of the values involved in the division must be a number with a decimal point. For example, 5.0 / 4 is 1.25 and 10 / 4.0 is 2.5.


public class Exercise_11 {

    public static void main(String[] strings) {

        double birthRateInSeconds = 7.0;
        double deathRateInSeconds = 13.0;
        double newImmigrantInSeconds = 45.0;



        double currentPopulation = 312032486;

        double secondsInYears = 60 * 60 * 24 * 365;

        double numBirths = secondsInYears / birthRateInSeconds;
        double numDeaths = secondsInYears / deathRateInSeconds;
        double numImmigrants = secondsInYears / newImmigrantInSeconds;

        for (int i = 1; i <= 5; i++) {
            currentPopulation += numBirths + numImmigrants - numDeaths;
            System.out.println("Year " + i + " = " + (int)currentPopulation);

        }


    }
}

Chapter 1 Exercise 10, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Average speed in miles) Assume a runner runs 14 kilometers in 45 minutes and 30 seconds. Write a program that displays the average speed in miles per hour. (Note that 1 mile is 1.6 kilometers.)


public class Exercise_10 {

    public static void main(String[] strings) {

        double kilometers = 14.0;
        double miles = kilometers / 1.6;

        double rate = (45.5 * 60.0 + 30.0) / (60.0 * 60.0);
        double milesPerHour = miles / rate;

        System.out.println(milesPerHour);


    }

}

Chapter 1 Exercise 9, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Area and perimeter of a rectangle) Write a program that displays the area and perimeter of a rectangle with the width of 4.5 and height of 7.9 using the following formula:
area = width * height


public class Exercise_09 {

    public static void main(String[] strings) {

        final double width = 4.5;
        final double height = 7.9;

        double area = width * height;

        System.out.printf("%.1f * %.1f = %.2f", width, height, area);
    }
}

Chapter 1 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Area and perimeter of a circle) Write a program that displays the area and perimeter of a circle that has a radius of 5.5 using the following formula:

public class Exercise_08 {

    private static final double radius = 5.5;

    public static void main(String[] args) {

        double perimeter = 2 * radius * Math.PI;
        double area = radius * radius * Math.PI;

        System.out.println("Perimeter = " + perimeter);
        System.out.println("Area = " + area);
    }
}

Chapter 1 Exercise 7, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Approximatep)  pi can be computed using the following formula:
4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) - (1.0/11))

public class Exercise_07 {

    public static void main(String[] args) {

        double pi = 4.0 * (1 - (1.0/3) + (1.0/5) - (1.0/7) + (1.0/9) - (1.0/11));
        System.out.println(pi); //
    }
}

Chapter 1 Exercise 6, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Summation of a series) Write a program that displays the result of

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9.


public class Exercise_06 {

    public static void main(String[] args) {
        int answer = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9;

        System.out.println("1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = " + answer);
    }
}

Chapter 1 Exercise 5, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Compute expressions) Write a program that displays the result of
(9.5 * 4.5 - 2.5 * 3) / (45.5 - 3.5)


public class Exercise_05 {

    public static void main(String[] arg) {

        System.out.println((9.5 * 4.5 - 2.5 * 3) / (45.5 - 3.5));
    }
}

Chapter 1 Exercise 4, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Print a table) Write a program that displays the following table:

a a^2 a^3
1 1 1
2 4 8
3 9 27
...........
4 16 64


public class Exercise_04 {

     public static void main(String[] args) {

         System.out.printf("%3s  |%5s  |%5s\n", "a", "a^2", "a^3");
         for (int i = 1; i <= 4; i++) {
             System.out.printf("%3d  |%5d  |%5d\n", i, i * i, i * i * i);
         }
     }
}

Chapter 1 Exercise 3, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Display a pattern) Write a program that displays the following pattern

           J    A  V     V  A
           J   A A  V   V  A A
        J  J  AAAAA  V V  AAAAA
         JJ  A     A  V  A     A
public class Exercise_03 {

    public static void main(String[] args) {

        System.out.println("   J    A  V     V  A");
        System.out.println("   J   A A  V   V  A A");
        System.out.println("J  J  AAAAA  V V  AAAAA");
        System.out.println(" JJ  A     A  V  A     A");
    }
}

Chapter 1 Exercise 2, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

(Display five messages) Write a program that displays Welcome to Java five times.
public class Exercise_02 {

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            System.out.println("Welcome to Java");
        }
    }
}

Chapter 1 Exercise 1, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

1.1 (Display three messages) Write a program that displays Welcome to Java,
Welcome to Computer Science, and Programming is fun.
  
public class Exercise_01 {

    public static void main(String[] args) {

        System.out.println("Welcome to Java");
        System.out.println("Welcome to Computer Science");
        System.out.println("Programming is fun");

    }
}