Archive for the ‘Java’ Category

Composition – Java

September 25, 2007

Emp.Java 

public class Emp

{

            private String firstName;

            private String lastName;

            private Date birthDate;

            private Date hireDate;

           

            //constructor to initialize name, birth date, and hire date

            public Emp (String first, String last, Date dateOfBirth, Date dateOfHire)

            {

                        firstName = first;

                        lastName = last;

                        birthDate = dateOfBirth;

                        hireDate = dateOfHire;

            }

           

            //convert Emp to String format

            public String toString()

            {

                        return String.format(“%s, %s Hired: %s Birthday: %s”,

                                    lastName, firstName, hireDate, birthDate);

            }

}

  Date.Java 

//Date class declaration

public class Date

{

            private int month;          //1-12

            private int day;  //1-31 based on month

            private int year; //any year

           

            //constructor: call checkMonth to confirm proper value for month

            //call checkDay to confirm proper value for day

            public Date(int theMonth, int theDay, int theYear)

            {

                        month = checkMonth(theMonth);          //validate month

                        year = theYear;                                    //could validate year

                        day = checkDay(theDay);                     //validate day

                        System.out.printf(“Date object constructor for date %s\n”, this);

            }

           

 

            //utility method to confirm proper month value

            private int checkMonth (int testMonth)

            {

                        if (testMonth>0 && testMonth <=12)   //validate month

                                    return testMonth;

                                    else                                                      //month is invalid

                                    {

                                    System.out.printf(“Invalid month (%d) set to 1.”, testMonth);

                                    return 1;           //maintain object in consistent state

                                    }

            }

           

            //utility method to confirm proper day value based on month and year

            private int checkDay (int testDay)

            {         

                        //0 is ignored since daysPerMonth[0]=0 represents 0 months

                        //Month starts on the 2nd element after 0 (from 1-12)

                        int daysPerMonth[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

                       

                        //check if day in range for month

                        if (testDay >= 1 && testDay <= daysPerMonth[month])

                                    return testDay;

                                   

                        //check for leap year

                        if (month == 2 && testDay == 29 && (year % 400==0 ||

                                    (year % 4 == 0 && year % 100 != 0)))

                                    return testDay;

                                   

                        System.out.printf(“Invalid day (%d) set to 1.”, testDay);

                        return 1;           //maintain object in consistent state

            }

           

            //return a String of the form month/day/year

            //automatically invoked even without calling this method

            public String toString()

            {

                        return String.format(“%d/%d/%d”, month, day, year);

            }

}

      EmpTest.Java 

//composition demonstration

public class EmpTest

{

            public static void main (String args[])

            {

                        Date birth = new Date(7,0,1980);

                        Date hire = new Date(9,5,2007);

           

                        Emp employee = new Emp(“Ana”, “Santos”, birth, hire);

                       

                        System.out.println(employee);

            }

}

Activity

September 21, 2007

Create class SavingsAccount.  Use a static variable annualInterestRate to store the annual interest rate for all account holders. Each object of the class contains a private instance variable savingsBalance indicating the amount the saver currently has on deposit.  Provide method calculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12 – this interest should be added to savingsBalance.  Provide a static method modifyInterestRate that sets the annualInterestRate to a new value.

Write a program to test class SavingsAccount.  Instantiate two savingsAccount objects, saver1 and saver2, with balances of P2000.00 and P3000.00, respectively.  Set annualInterestRate to 4%, then calculate the monthly interest and print the new balances for both savers.  Then set the annualInterestRate to 5%, calculate the next month’s interest and print the new balances for both savers.

Note:    implement Accessor and Mutator Methods

            Apply Garbage collector

            Grades will be dependent to a well-written code and readability of your program.

Java – Activity 2

July 24, 2007

Object – Instance of a class

 While working with classes, we declare a reference variable of a class type and then, typically, using the operator new, we instantiate an object of that class type and store the address of the object into the reference variable.

The statement:  Sum j = new Sum(); 

instantiate an object called j from class Sum.

Using the operator new to create a class object is called instantiation of the class.

public class Sum

{ double n1, n2;

   void Outs(double a, double b)

   { System.ou.println(“The sum is ” + s);

   }

   public static void main(String[] args)

   { Sum j = new Sum();

      j.n1 = 6.5;

      j.n2 = 8.5;

      j.Outs(j.n1, j.n2);

   }

}

Java – Activity1.1

July 11, 2007

Activity1.1            : Command line programming – Method Overloading

Program File         : MethodOverload.java

Procedures            : 1. Type the program file.     

                               : 2. Save/Compile the program.                       

                               : 3. Using the Command Prompt (C:\>), execute the following:

                                    Path = C:\jdk\bin (or look for the equivalent directory)                                   

                                    Javac MethodOverload.java          (compiling the program)                  

                               :  4. Execute the program with test data.                            

                                     Scenario1:       Java MethodOverload 5

                                    Output:            The area is : 78.54                             

                                    Scenario2:       Java MethodOverload 5 3                             

                                    Output:            The area is : 12.5 

                                     Scenario3:       Java MethodOverload                                      

                                     Output:            error 

                                     Scenario4:        Java MethodOverload 1 2 3                                     

                                     Output:            error

 

public class MethodOverload

{ static double n1,n2,a;

            static double area(double n1)

            { a = 3.1416 * n1*n1;

               return a;

            }

static double area(double n1, double n2)

{ a = 1/2.0 * n1*n1;

   return a;

}

public static void main(String[] args)

{

               if (args.length>2 || args.length<1)

                        System.out.println(“error”);

                        else

                        {

                            n1 = Double.parseDouble(args[0]);

                             if (args.length==1)

                                       System.out.println(“The area is: “+ area(n1));

                                      else

                                      {

                                            n2 = Double.parseDouble(args[1]);

                                         System.out.println(“The area is: “+ area(n1,n2));

                                      }

                        }

            }

}

Java – Activity1

July 11, 2007

Activity1: Command line programming.

Program File   : Sum.java

Procedures     : 1. Type the program file.

                        : 2. Save/Compile the program.

                        : 3. Using the Command Prompt (C:\>), execute the following:

                                    Path = C:\jdk\bin        (or look for the equivalent directory)

                                    Javac Sum.java          (compiling the program)

                                    Java Sum 2 3              (running the program with test data)

                        : 4. The result should look like this:

                                    The sum is: 5.0

                        : 5. If the command

                                    java Sum 5

or

java Sum 1 2 3

is executed, a message “Invalid number of inputs!” will be displayed.

 

public class Sum

{

            static double n1, n2;

           

            public static void main( String args[] )

            {

                        int numArgs = args.length;

                       

                        if( numArgs >2 || numArgs < 2 )

                                    System.out.println( “Invalid number of inputs.” );

                        else

                        {

                                    n1 = Double.parseDouble( args[0] );

                                    n2 = Double.parseDouble( args[1] );

                                               

                                    System.out.println( “The sum is: ” + (n1+n2));

                        }

            }

}

 

Note:   In the command Java Sum 2 3, the first number 2 is args[0] while 3 is args[1].

            The method length will count the number of arguments based from the user inputs.

Java – Activity3

July 11, 2007

Activity3: Reading a record from a source file and storing the results to an output file.

Program File   : StudGrade.java

Source File     : score.txt

Output File     : result.txt

Procedures     : 1. Type the program file.

                          2. Create a source file (score.txt) and provide a record, like:

                                    Sandy Tan 90.5 82.4 70

                          3. Compile the program.

                          4. Execute the program.

                          5. Open the output file (result.txt) and the result should look like this:

                                    Student Name: Sandy Tan

                                    Test Scores: 90.50 82.40 70.00

                                    Average: 80.97

                                   

import java.io.*;

import java.util.*;

public class StudGrade

{

            public static void main(String[] args) throws FileNotFoundException

            {

                        double score1, score2, score3, average;

                        String firstName, lastName;

                       

                        Scanner inputFile = new Scanner(new FileReader(“g:score.txt”));

                       

                        PrintWriter outputFile = new PrintWriter(“g:result.txt”);

                       

                        firstName = inputFile.next();

                        lastName  = inputFile.next();

                        score1    = inputFile.nextDouble();

                        score2    = inputFile.nextDouble();

                        score3    = inputFile.nextDouble();

                       

                        average   = (score1+score2+score3)/3;

                       

                        outputFile.println(“Student Name: ” + firstName + ” ” + lastName);

                        outputFile.printf(“Test Scores: %.2f %.2f %.2f %n”, score1, score2, score3);

                        outputFile.printf(“Average : %.2f”, average);

                       

                        inputFile.close();

                        outputFile.close();

            }

}


Design a site like this with WordPress.com
Get started