Monday, September 12, 2016

JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS

Questions: Temperature Conversions

Implement the following integer methods:
a) Method celsius returns the Celsius equivalent of a Fahrenheit temperature, using the calculation


celsius = 5.0 / 9.0 * ( fahrenheit - 32 );


b) Method fahrenheit returns the Fahrenheit equivalent of a Celsius temperature, using the calculation


fahrenheit = 9.0 / 5.0 * celsius + 32;


c) Use the methods from parts (a) and (b) to write an application that enables the user either to enter a Fahrenheit temperature and display the Celsius equivalent or to enter a Celsius temperature and display the Fahrenheit equivalent.


Solutions: Temperature Conversions

// Program converts Fahrenheit to Celsius. and vice versa.
import java.util.Scanner;

public class TemperatureConversion
{
  public static void main (String [] args)
  {
  Scanner input = new Scanner( System.in );
     
      int choice; // the user's choice in the menu
     
      do
      {
         // print the menu
         System.out.println( "1 Fahrenheit to Celsius" );
         System.out.println( "2 Celsius to Fahrenheit" );
         System.out.println( "3 Exit" );
         System.out.print( "Choice: " );
         choice = input.nextInt();
        
         if ( choice != 3 )
         {
            System.out.print( "Enter temperature: " );
            int oldTemperature = input.nextInt();

            // convert the temperature appropriately
           
            switch ( choice )
            {
               case 1:
                  System.out.printf( "%d Fahrenheit is %d Celsius\n",
                     oldTemperature, celsius( oldTemperature ) );
                  break;

               case 2:
                  System.out.printf( "%d Celsius is %d Fahrenheit\n",
                    oldTemperature, fahrenheit( oldTemperature ) );
                  break;
                 
              default:
                    System.out.println("Wrong Choice, try again!");
            } // end switch
         } // end if
    
      }// end do
     
      while ( choice != 3 );
  
      } // end method main

       
   // return Celsius equivalent of Fahrenheit temperature
   public static int celsius( int fahrenheitTemperature )
   {
      return ( (int) ( 5.0 / 9.0 * ( fahrenheitTemperature - 32 ) ) );
   } // end method celsius

   // return Fahrenheit equivalent of Celsius temperature
   public static int fahrenheit( int celsiusTemperature )
   {
      return ( (int) ( 9.0 / 5.0 * celsiusTemperature + 32 ) );
   } // end method fahrenheit
} // end class TemperatureConversion


JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS

Question: Reversing Digits

Write a method that takes an integer value and returns the number with its digits reversed. For example, given the number 7631, the method should return 1367. Incorporate the method into an application that reads a value from the user and displays the result.


Solution: Reversing Digits

import java.util.Scanner;

public class ReverseNumber {

   public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
       System.out.print("Enter the number to be reversed : ");
       int entry = input.nextInt();
       int result = reverse(entry);
       System.out.println("The reversed number is " + result);
   }

   public static int reverse(int n) {
       int result = 0;
       int rem;
       while (n > 0) {
           rem = n % 10;
           n = n / 10;
           result = result * 10 + rem;
       }
       return result;
   }
}

JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS



Question: Perfect Numbers 

An integer number is said to be a perfect number if its factors, including
1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write a method isPerfect that determines if parameter number is a perfect number. Use this method in an application that displays all the perfect numbers between 1 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect. Challenge the computing power of your computer by testing numbers much larger than 1000. Display the results. 


Solution: Perfect Numbers 

/**
 Author: Free Coder
 www.freecoder247.blogspot.com
 */

public class PerfectNumbers {

  public static void main(String[] args) {

    // loop and print perfect numbers between 1 and 1000 using our perfectNum() method
    for (int num = 1; num <= 1000; num++) {
      if (isPerfect(num)) {
        System.out.println("The number " + num + " is a perfect number!");
      }
    }
 
  } // end main()

 
 
  public static Boolean isPerfect(int num) {
 
    // declare a variable to hold the sum of num's factors
    int sum = 0;
 
    // loop over all the numbers up to 'num' to determine if they are factors
    // if they are then add them to 'sum'
    for (int factor = 1; factor < num; factor++) {
      if (num % factor == 0) {
        sum += factor;
      }
    }
 
    // if 'sum' is equal to the number passed in then it's a perfect number
    if (sum == num) {
      return true;
    } else {
      return false;
    }
 
  } // end public method isPerfect()

} // end PerfectNumbers class
 

JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS



Question: Parking Charges

A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time.Write an application that calculates and displays the parking charges for each customer who parked in the garage yesterday. You should enter the hours parked for each customer. The program should display the charge for the current customer and should calculate and display the running total of yesterday’s receipts. It should use the method calculateCharges to determine the charge for each customer.  


Solution: Parking Charges

//Author: Free Coder
//www.freecoder247.blogspot.com

//Parking Charges.java
//This program calculates customers parking charges 
import java.util.Scanner;

public class ParkingCharges
      {
     
    public static void main ( String [] args)
    {
      Scanner input = new Scanner (System.in);
     
      double totalReceipts=0.0;
      double fee;
      double hours;
     
      System.out.print("Enter number of hours (a negative to quit): " );
      hours=input.nextDouble();
     
      while (hours >=0.0)
      {
      fee=calculateCharge(hours);
      totalReceipts += fee;
      System.out.printf("Current charge: N%.2f, Total receipts: N%.2f\n", fee, totalReceipts );
      System.out.print("Enter number of hours (a negative to quit)");
      hours=input.nextDouble();
      }//end while
    }// method main     
    

    private static double calculateCharge(double hours)
    {
       /*final*/ double minPark= 2.0;

       /*final*/ double maxPark= 10.0;

       /*final*/ double maxHours= 24.0;

       /*final*/ double minHours= 3.0;

       /*final*/ double hourEx= 0.5;

       double fee;
     
       fee= minPark;
       
      if ( hours <= minHours )

          fee = minPark;
          
     
      if ( hours > minHours && hours < maxHours )
          fee = hourEx*(Math.ceil(hours) - minHours) + minPark;
     
       if ( hours == maxHours )

          fee = maxPark;
        
      
       return fee;
    } // method calculateCharge

 } // class ParkingCharges


JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS



Question: Multiples 

Write a method isMultiple that determines, for a pair of integers, whether the second integer is a multiple of the first. The method should take two integer arguments and return true if the second is a multiple of the first and false otherwise. [Hint: Use the remainder operator.] Incorporate this method into an application that inputs a series of pairs of integers (one pair at a time) and determines whether the second value in each pair is a multiple of the first.

Solution: Multiples

//Author: Free Coder
//www.freecoder247.blogspot.com
//MultiplesFinder.java
//This program accepts two numbers and finds whether the second number is a multiple of the first.

import java.util.Scanner;

public class MultiplesFinder
{
  public static void main ( String [] args)
  {
    //create Scanner for input
    Scanner input = new Scanner (System.in);
     
      //prompt for and input two integer numbers
   
    System.out.print("Enter two integer values separated by spaces: ");
      int num1= input.nextInt();
      int num2= input.nextInt();
     
      //determine whether the second number is a multiple of the first
     
      Boolean result = isMultiple(num1,num2);     
    
        System.out.printf("%S ", result);
  }// end of main
 
 
  public static Boolean isMultiple(int num1,int num2)
  {
    Boolean result;
    int quotient = num2%num1;
    if (quotient == 0)
      result = true;
      else
      result = false;
      return result;
  }// end method isMultiple

}//end class



    

JAVA HOW TO PROGRAM, NINTH EDITION, DEITEL: CHAPTER SIX SOLUTIONS



Question: Guess The Number


Write an application that plays “guess the number” as follows: Your program chooses the number to be guessed by selecting a random integer in the range 1 to 1000. The application displays the prompt Guess a number between 1 and 1000. The player inputs a first guess. If the player's guess is incorrect, your program should display Too high. Try again. or Too low. Try again. to help the player “zero in” on the correct answer. The program should prompt the user for the next guess. When the user enters the correct answer, display Congratulations. You guessed the number!, and allow the user to choose whether to play again. [Note: The guessing technique employed in this problem is similar to a binary search, which is discussed in Chapter 19, Searching, Sorting and Big O.]




Solution: Guess The Number


//Author: Free Coder
//www.freecoder247.blogspot.com

import java.util.Scanner;
import java.util.Random;

public class GuesstheNumber {
 
public static void main (String[] args) {
   
Random rand = new Random ();
int numberToGuess = rand.nextInt (1000);
int numberOfTries = 0;
Scanner input = new Scanner (System.in);
int guess;
boolean win = false;
   
while (win == false) {
      

System.out.println ("Guess a number between 1 and 1000: ");
guess = input.nextInt();
numberOfTries++;
     
if (guess == numberToGuess) {
win=true;
}
else if (guess < numberToGuess) {
System.out.println("Your guess is too low");
}
else if (guess > numberToGuess) {
System.out.println("Your guess is too high");
}
}
   
System.out.println("You win!");
System.out.println("The number was " + numberToGuess);
System.out.println("It took you " + numberOfTries + " tries ");
   
}
}