Gaddis-ch5

5-12 SalesReport

posted Apr 3, 2014, 10:11 AM by Dlovan ismail

/*
This program opens a file containing the sales
amounts for 30 days. It calculates and displays
the total sales and average daily sales.
*/

package salesreport;
import java.util.Scanner;                    // For the Scanner class.
import java.io.*;                                     // For file I/O classes
import java.text.DecimalFormat;   // For the DecimalFormat class
import javax.swing.JOptionPane;   // For the JOptionPane class

public class SalesReport 
{
        public static void main(String[] args)throws IOException 
        { 
            final int NUM_DAYS = 30;  // Number of days of sales.
            String filename;                   // The name of the file to open.
            double totalSales;             // Total sales for period.
            double averageSales;       // Average daily sales.

            // Get the name of the file.
            filename = getFileName();

            // Get the total sales from the file.
            totalSales = getTotalSales(filename);

            // Calculate the average.
            averageSales = totalSales / NUM_DAYS;

            // Display the total and average.
            displayResults(totalSales, averageSales);

            System.exit(0);

        }

        /*
        The getFileName method prompts the user to enter
        the name of the file to open.
        @return A reference to a String object containing
                  the name of the file.
        */

        public static String getFileName()
        {
            String file;      // To hold the file name.

            // Prompt the user to enter afile name.
            file = JOptionPane.showInputDialog("Enter the name of the file\n"
                                       +"containing 30 days of sales amount.");

            // Return the name.
            return file;
        }

        /*
        The getTotalSales method opens a file and
        reads the daily sales amounts, accumulating
        the total. The total is returned.
        @param filename The name of the file to open.
        @return The total of the sales amounts.
        */

        public static double getTotalSales(String filename)throws IOException
        {
            double total = 0.0;    // Accumulator.
            double sales;              // A daily sales amount.

            // Open the file.
            File file = new File(filename);
            Scanner inputFile = new Scanner(file);

            // This loop processes the lines read from the file.
            // until the end of the file is encountered.
            while(inputFile.hasNext())
            {
                // Read a double from the file.
                sales = inputFile.nextDouble();

                // Add sales to the value already in total.
                total += sales;
            }

            // Close the file.
            inputFile.close( );

            // Return the total sales.
            return total;
        }

        /*
        The displayResults method displays the total and
        average daily sales.
        @param total The total sales.
        @param avg The average daily sales.
        */

        public static void displayResults(double total , double avg)
        {
            // Create a DecimalFormat object capable of formatting a dollar amount.
            DecimalFormat dollar = new DecimalFormat( "#,###.00");

            // Display the total and average sales.
            JOptionPane.showMessageDialog(null,"The total sales for the period is $"+
                  dollar.format(total)+"\nThe average daily sales were $"+dollar.format(avg));
        }
}

5-11 ReturnString

posted Apr 3, 2014, 9:14 AM by Dlovan ismail   [ updated Apr 3, 2014, 9:15 AM ]

/*
This program demonstrates a method that
returns a reference to a String object.
*/

package returnstring;

public class ReturnString 
{
        public static void main(String[] args) 
        {
            String customerName;

            customerName = fullName("John","Martin");
            System.out.println(customerName);
        }

        /*
        The fullName method accepts two String arguments
        containing a first and last name. It concatenates
        them into a single String object.
        @param first The first name,
        @param iast The last name.
        @return A reference to a String object containing
                  the first and last names.
        */

        public static String fullName(String first , String last)
        {
            String name;

            name = first + " " + last;
            return name;
        }
    
}

5-10 CupConverter

posted Apr 3, 2014, 9:02 AM by Dlovan ismail   [ updated Apr 3, 2014, 9:17 AM ]

//This program converts cups to fluid ounces.

package cupconverter;
import javax.swing.JOptionPane;

public class CupConverter 
{
        public static void main(String[] args) 
        {
           double cups;       // To hold the number of cups
           double ounces;  // To hold the number of ounces

           // Get the number of cups.
           cups = getCups();

           // Convert the cups to fluid ounces.
           ounces = cupsToOunces(cups);

           // Display the results.
           displayResults(cups,ounces);
           System.exit(0);
        }

        /*
        The getCups method prompts the user to enter a number
        of cups.
        @return The number of cups entered by the user.
        */

        public static  double getCups()
        {
            String input;             // To hold input.
            double numCups;   // To hold cups.

            // Get the number of cups from the user.
            input = JOptionPane.showInputDialog(
            "This program converts measurements\n"+
            "in cups to fluid ounces. For your\n"+
            "reference the formula is:\n"+
            "     1 cup = 8 fluid ounces\n\n"+
            "Enter the number of cups.");

            // Convert the input to a double
            numCups = Double.parseDouble(input);

            // Return the number of cups.
            return numCups;
        }

        /*
        The cupsToOunces method converts a number of
        cups to fluid ounces, using the formula
        1 cup = 8 fluid ounces.
        @param numCupa The number of cups to convert.
        @return The number of ounces.
        */

        public static double cupsToOunces(double numCups)
        {
            return numCups * 8.0;
        }

        /*
        The displayResults method displays a message showing
        the results of the conversion.
        @param cups A number of cups.
        @param ounces A number of ounces.
        */

        public static void displayResults(double cups, double ounces)
        {
            // Display the number of ounces
            JOptionPane.showMessageDialog(null, cups +" cups equals "+ounces+ " fluid ounces.");
        }
}

5-9 ValueReturn

posted Mar 29, 2014, 10:42 AM by Dlovan ismail

//This program demonstrates a value-returning Method.

package valuereturn;

public class ValueReturn
{
        public static void main(String[] args)
        {
            int total, valuel = 20, value2 = 40;

            // Call the sum method, passing the contents of valuel and valuo2 as arguments.
            // Assign the return value to the total variable.
            total = sum(valuel, value2);

            // Display the contents of all these variables.
            System.out.println("The sum of " + valuel + " and " + value2 + " is " + total) ;

        }

        /* 
           The sum method returns the sum of its two parameters.
           @param numl The first number to be added.
           @param num2 The second number to be added.
           @return The sum of numl and num2.
        */

        public static int sum(int numl, int num2)
        {
            int result;   // result is a local variable

            // Assign the value of numl + num2 to result.
            result = numl + num2;

            // Return the value in the result variable.
            return result;

        }
    
}

5-8 LocalVar

posted Mar 29, 2014, 10:27 AM by Dlovan ismail

//Thls program demonstrates that two methods may have local variables with the same name.

package localvar;

public class LocalVar 
{
        public static void main(String[] args) 
        {
            texas();
            California();
        }

        // The texas method has a local variable named birds.

        public static void texas()
        {
            int birds = 5000;

            System.out.println("In texas there are " + birds + " birds.");

        }

        // The California method also has a local variable named birds.

        public static void California()
        {
            int birds = 3500;

            System.out.println("In California there are " + birds + " birds.");

        }
    
}

5-7 PassString

posted Mar 29, 2014, 10:02 AM by Dlovan ismail

//This program demonstrates that String arguments cannot be changed.

package passstring;

public class PassString 
{

        public static void main(String[] args) 
        {
            // Create a String object containing "Shakespeare".
            // The name variable references the object.
            String name = "Shakespeare";

            // Display the String referenced by the name variable.
            System.out.println("In main, the name is " + name);

            // Call the changeName method, passing the contents of the name variable as an argument.
            changeName(name);

            // Display the String referenced by the name variable.
            System.out.println("Back in main, the name is " + name);

        }

        //The changeName method accepts a String as its argument and assigns the str parameter to a new String.

        public static void changeName(String str)
        {
            // Create a String object containing "Dickens".
            // Assign its address to the str parameter variable.
            str = "Dickens";

            // Display the String referenced by str.
            System.out.println("In changeName, the name is now " + str);

        }
    
}

5-6 PassByValue

posted Mar 29, 2014, 9:51 AM by Dlovan ismail

//This program demonstrates that only a copy of an argument is passed into a method.

package passbyvalue;

public class PassByValue 
{
        public static void main(String[] args)
        {
          int number = 99; // number starts with 99

          // Display the value in number.
          System.out.println( "number is " + number);

          // Call changeMe, passing the value in number as an argument.

          changeMe(number);

          // Display the value in number again.
          System.out.println("number is " + number);

        }

        //The changeMe method accepts an argument and then changes the value of the parameter.

        public static void changeMe(int myValue)
        {
            System.out.println("I an changing the value.");

            //Change the myValue parameter variable to 0.
            myValue = 0;

            // Display the value in myValue.
            System.out.println("Now the value is " + myValue);

        }
    
}

5-5 PassArg

posted Mar 29, 2014, 9:32 AM by Dlovan ismail

//This program demonstrates a method with a parameter.

package passarg;

public class PassArg
{
        public static void main(String[] args) 
        {
            int x = 10;

            System.out.println("I am passing values to displayValue.");

            displayValue(5);                                                 // Pass 5
            displayValue(x);                                                 // Pass 10
            displayValue(x * 4);                                           // Pass 40
            displayValue(Integer.parseInt("700"));      // Pass 700

            System.out.println("Now I am back in main.");
        }  

        //The displayValue method displays the value of its integer parameter.

        public static void displayValue(int num)
        {
            System.out.println("The value is " + num);
        }
   
}

5-4 DeepAndDeeper

posted Mar 29, 2014, 9:18 AM by Dlovan ismail

//This program demonstrates hierarchical method call.

package deepanddeeper;

public class DeepAndDeeper 
{
        public static void main(String[] args)
        {
            System.out.println("I am starting in main.");
            deep();
            System.out.println("Now I am back in main.");
        } 

        //The deep method displays a message and then calls the deeper method. 

        public static void deep()
        {
            System.out.println("I am now in deep.");
            deeper();
            System.out.println("Now I am back in deep.");
        }

        //The deeper method simply displays a message.

        public static void deeper()
        {
            System.out.println("I am now in deeper.");
        }
}

5-3 CreditCard

posted Mar 8, 2014, 10:01 AM by Dlovan ismail   [ updated Mar 8, 2014, 10:02 AM by Karwan Jacksi ]

//This program uses two void methods.

package creditcard;
import javax.swing.JOptionPane;

public class CreditCard
{
    public static void main(String[] args) 
    {
            double salary;        // Annual salary
            int creditRating;   // Credit rating
            String input;           // To hold the user's input

            // Get the user's annual salary.
            input = JOptionPane.showInputDialog("What is your annual salary?");
            salary = Double.parseDouble(input);

            // Get the user's credit rating (1 through 10).
            input = JOptionPane.showInputDialog("on a scale of "
                    +"1 through 10, what is your credit rating?\n"
                    +"(10 = excellent, 1 = very bad)");
            creditRating = Integer.parseInt(input);

            // Determine whether the user qualifies.
            if (salary >= 20000 && creditRating >= 7)
                qualify();
            else
                noQualify();

            System.exit(0);

        }

        /*
        The qualify method informs the user that he
        or she qualifies for the credit card.
        */

        public static void qualify()
        {
            JOptionPane.showMessageDialog(null, "Congratulations! You qualify for the credit card!");
        }

        /*
        The noQualify method informs the user that he
        or she does not qualify for the credit card.
        */

        public static void noQualify()
        {
            JOptionPane.showMessageDialog(null, "I'm sorry. You do not qualify for the credit card.");
        }
    
}

1-10 of 12