Showing posts with label Methods. Show all posts
Showing posts with label Methods. Show all posts

Account - Java Sample Program

// Account.java
// Account class with a constructor to validate and 
// initialize instance variable balance of type double.

public class Account
{   
   private double balance; // instance variable that stores the balance

   // constructor  
   public Account( double initialBalance )
   {
      // validate that initialBalance is greater than 0.0; 
      // if it is not, balance is initialized to the default value 0.0
      if ( initialBalance > 0.0 ) 
         balance = initialBalance; 
   } // end Account constructor

   // credit (add) an amount to the account
   public void credit( double amount )
   {      
      balance = balance + amount; // add amount to balance 
   } // end method credit

   // return the account balance
   public double getBalance()
   {
      return balance; // gives the value of balance to the calling method
   } // end method getBalance
} // end class Account


// AccountTest.java
// Inputting and outputting floating-point numbers with Account objects.
import java.util.Scanner;

public class AccountTest
{
   // main method begins execution of Java application
   public static void main( String[] args ) 
   {
      Account account1 = new Account( 50.00 ); // create Account object
      Account account2 = new Account( -7.53 ); // create Account object

      // display initial balance of each object
      System.out.printf( "account1 balance: $%.2f\n", 
         account1.getBalance() );
      System.out.printf( "account2 balance: $%.2f\n\n", 
         account2.getBalance() );
      
      // create Scanner to obtain input from command window
      Scanner input = new Scanner( System.in );
      double depositAmount; // deposit amount read from user

      System.out.println( "Enter deposit amount for account1: " ); // prompt
      depositAmount = input.nextDouble(); // obtain user input
      System.out.printf( "\nadding %.2f to account1 balance\n\n", 
         depositAmount );
      account1.credit( depositAmount ); // add to account1 balance

      // display balances
      System.out.printf( "account1 balance: $%.2f\n", 
         account1.getBalance() );
      System.out.printf( "account2 balance: $%.2f\n\n", 
         account2.getBalance() );

      System.out.print( "Enter deposit amount for account2: " ); // prompt
      depositAmount = input.nextDouble(); // obtain user input
      System.out.printf( "\nadding %.2f to account2 balance\n\n", 
         depositAmount );
      account2.credit( depositAmount ); // add to account2 balance

      // display balances
      System.out.printf( "account1 balance: $%.2f\n", 
         account1.getBalance() );
      System.out.printf( "account2 balance: $%.2f\n", 
         account2.getBalance() );
   } // end main
} // end class AccountTest

Grade Book 3 - Java Sample Program

// GradeBook.java
// GradeBook class that contains a courseName instance variable 
// and methods to set and get its value.

public class GradeBook
{
   private String courseName; // course name for this GradeBook

   // method to set the course name
   public void setCourseName( String name )
   {
      courseName = name; // store the course name
   } // end method setCourseName

   // method to retrieve the course name
   public String getCourseName()
   {
      return courseName;
   } // end method getCourseName

   // display a welcome message to the GradeBook user
   public void displayMessage()
   {
      // calls getCourseName to get the name of 
      // the course this GradeBook represents
      System.out.printf( "Welcome to the grade book for\n%s!\n", 
         getCourseName() );
   } // end method displayMessage
} // end class GradeBook




// GradeBookTest.java
// Creating and manipulating a GradeBook object.
import java.util.Scanner; // program uses Scanner

public class GradeBookTest
{
   // main method begins program execution
   public static void main( String[] args )
   { 
      // create Scanner to obtain input from command window
      Scanner input = new Scanner( System.in );

      // create a GradeBook object and assign it to myGradeBook
      GradeBook myGradeBook = new GradeBook(); 

      // display initial value of courseName
      System.out.printf( "Initial course name is: %s\n\n",
         myGradeBook.getCourseName() );

      // prompt for and read course name
      System.out.println( "Please enter the course name:" );
      String theName = input.nextLine(); // read a line of text
      myGradeBook.setCourseName( theName ); // set the course name
      System.out.println(); // outputs a blank line

      // display welcome message after specifying course name
      myGradeBook.displayMessage();
   } // end main
} // end class GradeBookTest


Grade Book - Java Sample Program


// GradeBook.java
// Class declaration with one method.

public class GradeBook
{
   // display a welcome message to the GradeBook user
   public void displayMessage()
   {
      System.out.println( "Welcome to the Grade Book!" );
   } // end method displayMessage
} // end class GradeBook


// GradeBookTest.java
// Creating a GradeBook object and calling its displayMessage method.

public class GradeBookTest
{
   // main method begins program execution
   public static void main( String[] args )
   { 
      // create a GradeBook object and assign it to myGradeBook
      GradeBook myGradeBook = new GradeBook(); 

      // call myGradeBook's displayMessage method
      myGradeBook.displayMessage(); 
   } // end main
} // end class GradeBookTest

Circle (User Define Classes) - Java Sample Program

public class Circle
{
private double radius;

//Default constructor
//Sets the radius to 0
Circle()
{
radius = 0;
}

//Constructor with a parameter
//Sets the radius to the value specified by the parameter r.
Circle(double r)
{
radius = r;
}

//Method to set the radius of the circle.
//Sets the radius to the value specified by the parameter r.
public void setRadius(double r)
{
radius = r;
}

//Method to return the radius of the circle.
//Returns the radius of the circle.
public double getRadius()
{
return radius;
}

//Method to compute and return the area of the circle.
//Computes and returns the area of the circle.
public double area()
{
return Math.PI * Math.PI * radius;
}

//Method to compute and return the perimeter of the circle.
//Computes and returns the area of the circle.
public double perimeter()
{
return 2 * Math.PI * radius;
}

//Method to return the radius, area, perimeter of the circle
//as a string.
public String toString()
{
return String.format("Radius = %.2f, Perimeter = %.2f"+ ", Area = %.2f%n", radius, perimeter(), area());
}
}


We leave the UML class diagram of the class Circle as an exercise for you.
The following program shows how to use the class Circle in a program.
// Program to test various operations of the class Circle.

import java.util.*; //Line 1
public class TestProgCircle //Line 2
{ //Line 3

static Scanner console = new Scanner(System.in); //Line 4

public static void main(String[] args) //Line 5
{ //Line 6

Circle firstCircle = new Circle(); //Line 7
Circle secondCircle = new Circle(12); //Line 8

double radius; //Line 9

System.out.println("Line 10: firstCircle: " + firstCircle); //Line 10

System.out.println("Line 11: secondCircle: " + secondCircle); //Line 11

System.out.print("Line 12: Enter the radius: "); //Line 12

radius = console.nextDouble(); //Line 13

System.out.println(); //Line 14

firstCircle.setRadius(radius); //Line 15

System.out.println("Line 16: firstCircle: " + firstCircle ); //Line 16

if (firstCircle.getRadius() > secondCircle.getRadius()) //Line 17
System.out.println("Line 18: The radius of "+ "the first circle is greater than "+ "the radius of the second circle. "); //Line 18
else if (firstCircle.getRadius()< secondCircle.getRadius()) //Line 19
System.out.println("Line 20: The radius of "+ "the first circle is less than the " + "radius of the second circle. "); //Line 20
else //Line 21
System.out.println("Line 22: The radius of " + "both the circles are the same."); //Line 22
}//end main //Line 23
} //Line 24

Sample Sample Output:

Line 10: firstCircle: Radius = 0.00, Perimeter = 0.00, Area = 0.00
Line 11: secondCircle: Radius = 12.00, Perimeter = 75.40, Area = 118.44
Line 12: Enter the radius: 10
Line 16: firstCircle: Radius = 10.00, Perimeter = 62.83, Area = 98.70
Line 20: The radius of the first circle is less than the radius of the second circle.

The preceding program works as follows. The statement in Line 7 creates the object
firstCircle and using the default constructor sets the radius to 0. The statement in
Line 8 creates the object secondCircle and sets the radius to 12. The statement in Line
9 declares the double variable radius. The statement in Line 10 outputs the radius, area,
and perimeter of the firstCircle. Similarly, the statement in Line 11 outputs the
radius, area, and perimeter of the secondCircle The statement in Line 12 prompts the
user to enter the value of radius. The statement in Line 13 stores the value entered by
the user in the variable radius. The statement in Line 15 uses the value of radius to set
the radius of firstCircle. The statement in Line 16 outputs the radius, area, and
perimeter of the firstCircle. The statements in Lines 17 to 23 compare the radius of
firstCircle and secondCircle and output the appropriate result.

Clock (User Define Classes) - Java Sample Program

//The definition of the class Clock is:

public class Clock
{
private int hr; //store hours
private int min; //store minutes
private int sec; //store seconds

//Default constructor
//Postcondition: hr = 0; min = 0; sec = 0
public Clock()
{
setTime(0, 0, 0);
}

//Constructor with parameters, to set the time
//The time is set according to the parameters.
//Postcondition: hr = hours; min = minutes;
// sec = seconds
public Clock(int hours, int minutes, int seconds)
{
setTime(hours, minutes, seconds);
}

//Method to set the time
//The time is set according to the parameters.
//Postcondition: hr = hours; min = minutes;
// sec = seconds
public void setTime(int hours, int minutes, int seconds)
{
if (0 <= hours && hours < 24)
hr = hours;
else
hr = 0;

if (0 <= minutes && minutes < 60)
min = minutes;
else
min = 0;

if (0 <= seconds && seconds < 60)
sec = seconds;
else
sec = 0;
}

//Method to return the hours
//Postcondition: the value of hr is returned
public int getHours()
{
return hr;
}

//Method to return the minutes
//Postcondition: the value of min is returned
public int getMinutes()
{
return min;
}

//Method to return the seconds
//Postcondition: the value of sec is returned
public int getSeconds()
{
return sec;
}

//Method to print the time
//Postcondition: Time is printed in the form hh:mm:ss
public void printTime()
{
if (hr < 10)
System.out.print("0");
System.out.print(hr + ":");

if (min < 10)
System.out.print("0");
System.out.print(min + ":");

if (sec < 10)
System.out.print("0");
System.out.print(sec);
}

//Method to increment the time by one second
//Postcondition: The time is incremented by one second
//If the before-increment time is 23:59:59, the time
//is reset to 00:00:00
public void incrementSeconds()
{
sec++;

if (sec > 59)
{
sec = 0;
incrementMinutes(); //increment minutes
}
}

//Method to increment the time by one minute
//Postcondition: The time is incremented by one minute
//If the before-increment time is 23:59:53, the time
//is reset to 00:00:53
public void incrementMinutes()
{
min++;

if (min > 59)
{
min = 0;
incrementHours(); //increment hours
}
}

//Method to increment the time by one hour
//Postcondition: The time is incremented by one hour
//If the before-increment time is 23:45:53, the time
//is reset to 00:45:53
public void incrementHours()
{
hr++;

if (hr > 23)
hr = 0;
}

//Method to compare two times
//Postcondition: Returns true if this time is equal to
// otherClock; otherwise returns false
public boolean equals(Clock otherClock)
{
return (hr == otherClock.hr
&& min == otherClock.min
&& sec == otherClock.sec);
}

//Method to copy time
//Postcondition: The instance variables of otherClock
// copied into the corresponding data
// are members of this time.
// hr = otherClock.hr;
// min = otherClock.min;
// sec = otherClock.sec;
public void makeCopy(Clock otherClock)
{
hr = otherClock.hr;
min = otherClock.min;
sec = otherClock.sec;
}

//Method to return a copy of time
//Postcondition: A copy of the object is created and
// a reference of the copy is returned
public Clock getCopy()
{
Clock temp = new Clock();
temp.hr = hr;
temp.min = min;
temp.sec = sec;
return temp;
}
}


//Program to test various operations of the class Clock
import java.util.*;
public class TestProgClock
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Clock myClock = new Clock(5, 4, 30); //Line 1
Clock yourClock = new Clock(); //Line 2

int hours; //Line 3
int minutes; //Line 4
int seconds; //Line 5

System.out.print("Line 6: myClock: "); //Line 6
myClock.printTime(); //Line 7

System.out.println(); //Line 8
System.out.print("Line 9: yourClock: "); //Line 9
yourClock.printTime(); //Line 10

System.out.println(); //Line 11
yourClock.setTime(5, 45, 16); //Line 12

System.out.print("Line 13: After setting "+ "the time - yourClock: "); //Line 13
yourClock.printTime(); //Line 14
System.out.println(); //Line 15

if (myClock.equals(yourClock)) //Line 16
System.out.println("Line 17: Both the " + "times are equal."); //Line 17
else //Line 18
System.out.println("Line 19: The two " + "times are not " + "equal."); //Line 19

System.out.print("Line 20: Enter hours, "+ "minutes, and seconds: "); //Line 20

hours = console.nextInt(); //Line 21
minutes = console.nextInt(); //Line 22
seconds = console.nextInt(); //Line 23
System.out.println(); //Line 24

myClock.setTime(hours, minutes, seconds); //Line 25

System.out.print("Line 26: New time of "+ "myClock: "); //Line 26
myClock.printTime(); //Line 27

System.out.println(); //Line 28
myClock.incrementSeconds(); //Line 29

System.out.print("Line 30: After "+ "incrementing the time by " + "one second, myClock: "); //Line 30

myClock.printTime(); //Line 31
System.out.println(); //Line 32

yourClock.makeCopy(myClock); //Line 33

System.out.print("Line 34: After copying "+ "myClock into yourClock, " + "yourClock: "); //Line 34

yourClock.printTime(); //Line 35

System.out.println(); //Line 36
}//end main
}
Sample Output:

Line 6: myClock: 05:04:30
Line 9: yourClock: 00:00:00
Line 13: After setting the time - yourClock: 05:45:16
Line 19: The two times are not equal.
Line 20: Enter hours, minutes, and seconds: 11 22 59
Line 26: New time of myClock: 11:22:59
Line 30: After incrementing the time by one second, myClock: 11:23:00
Line 34: After copying myClock into yourClock, yourClock: 11:23:00

Triangle of Stars - Void Method - Java Sample Program

// Program: Print a triangle of stars
// Given the number of lines, this program prints a triangle of stars.

import java.util.*;
public class TriangleOfStars
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int numberOfLines;
int numberOfBlanks;
int counter = 1;

System.out.print("Enter the number of star lines " + "(1 to 20) to be printed: ");

numberOfLines = console.nextInt();

System.out.println();

while (numberOfLines < 0 || numberOfLines > 20)
{
System.out.println("The number of star lines should " + "be between 1 and 20");
System.out.print("Enter the number of star lines " + "(1 to 20) to be printed: ");

numberOfLines = console.nextInt();

System.out.println ();
}

numberOfBlanks = 30;
for (counter = 1; counter <= numberOfLines; counter++)
{
printStars(numberOfBlanks, counter);
numberOfBlanks--;
}
} // end main

public static void printStars(int blanks, int starsInLine)
{
int count = 1;

for (count = 1; count <= blanks; count++)
System.out.print(" ");

for (count = 1; count <= starsInLine; count++)
System.out.print(" *");

System.out.println();
} //end printStars
}

Sample Output:

Enter the number of star lines (1 to 20) to be printed: 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *

In the method main, the user is first asked to specify how many lines of stars to print. (In
this program, the user is restricted to 20 lines because a triangular grid of up to 20 lines fits
nicely on the screen.) Because the program is restricted to only 20 lines, the while loop
in the method main ensures that the program prints the triangular grid of stars only if the
number of lines is between 1 and 20.

Largest Number (Revised) - Java Sample Program

// Program: Largest number
// This program determines the largest number of a set of 10 numbers.

import java.util.*;
public class LargestNumber
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
double num; //variable to hold the current number
double max; //variable to hold the larger number

int count; //loop control variable

System.out.println("Enter 10 numbers:");
num = console.nextDouble(); //Step 1
max = num; //Step 1

for (count = 1; count < 10; count++) //Step 2
{
num = console.nextDouble(); //Step 2a
max = larger(max, num); //Step 2b
}

System.out.println("The largest number is " + max); //Step 3
}

public static double larger(double x, double y)
{
double max;

if (x >= y)
max = x;
else
max = y;
return max;
}
}

Sample Output:

Enter 10 numbers:
10.5 56.34 73.3 42 22 67 88.55 26 62 11
The largest number is 88.55

Larger Number Using Methods - Java Sample Program

//The following program uses the method larger and main to determine the larger of two numbers:
//Program: Larger of two numbers

import java.util.*;
public class LargerNumber
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
double num1; //Line 1
double num2; //Line 2

System.out.println("Line 3: The larger of " + "5.6 and 10.8 is " + larger(5.6, 10.8)); //Line 3
System.out.print("Line 4: Enter two " + "numbers: "); //Line 4

num1 = console.nextDouble(); //Line 5
num2 = console.nextDouble(); //Line 6

System.out.println(); //Line 7
System.out.println("Line 8: The larger of " + num1 + " and " + num2 + " is "+ larger(num1, num2)); //Line 8
}

public static double larger(double x, double y)
{
double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
}

Sample Output:

Line 3: The larger of 5.6 and 10.8 is 10.8
Line 4: Enter two numbers: 34 43
Line 8: The larger of 34.0 and 43.0 is 43.0

Predefined Methods - Java Sample Program

//How to use the predefined methods
import static java.lang.Math.*;
import static java.lang.Character.*;

public class PredefinedMethods
{
public static void main(String[] args)
{
int x;
double u;
double v;

System.out.println("Line 1: Uppercase a is " + toUpperCase('a')); //Line 1

u = 4.2; //Line 2
v = 3.0; //Line 3

System.out.printf("Line 4: %.1f to the power " + "of %.1f = %.2f%n", u, v, pow(u, v)); //Line 4
System.out.printf("Line 5: 5 to the power of " + "4 = %.2f%n", pow(5, 4)); //Line 5

u = u + Math.pow(3, 3); //Line 6

System.out.printf("Line 7: u = %.2f%n", u); //Line 7

x = -15; //Line 8

System.out.printf("Line 9: The absolute value " + "of %d = %d%n", x, abs(x)); //Line 9
}
}


Sample Output:
Line 1: Uppercase a is A
Line 4: 4.2 to the power of 3.0 = 74.09
Line 5: 5 to the power of 4 = 625.00
Line 7: u = 31.20
Line 9: The absolute value of -15 = 15

This program works as follows: The statement in Line 1 outputs the uppercase letter that
corresponds to 'a', which is 'A'. In the statement in Line 4, themethod pow (of the class
Math) is used to output uv. In Java terminology, it is said that the method pow is called with the
(actual) parameters u and v. In this case, the values of u and v are passed to the method pow.

The statement in Line 5 uses the method pow to output 54. The statement in Line 6 uses the method
pow to determine 33, adds this value to the value of u, and then stores the new value into u.
Notice that in this statement, the method pow is called using the name of the class, which is
Math, and the dot operator. The statement in Line 7 outputs the value of u. The statement in
Line 8 stores -15 into x, and the statement in Line 9 outputs the absolute value of x.

Predefined Methods Class Character - Java Sample Program

class Character (Package: java.lang)

Example:

isLowerCase(ch)
ch is of type char. Returns true, if ch is a lowercase
letter; false otherwise.
Example:
isLowerCase('a') returns the value true
isLowerCase('A') returns the value false

isUpperCase(ch)
ch is of type char. Returns true, if ch is an uppercase
letter; false otherwise.
Example:
isUpperCase('B') returns the value true
isUpperCase('k') returns the value false

toLowerCase(ch)
ch is of type char. Returns the character that is the
lowercase equivalent of ch. If ch does not have the
corresponding lowercase letter, it returns ch.
Example:
toLowerCase('D') returns the value d
toLowerCase('*') returns the value *

toUpperCase(ch)
ch is of type char. Returns the character that is the
uppercase equivalent of ch. If ch does not have the
corresponding uppercase letter, it returns ch.
Example:
toUpperCase('j') returns the value J
toUpperCase('8') returns the value 8

Predefined Methods Class Math- Java Sample Program

class Math (Package: java.lang)

Example:

abs(-67) returns the value 67

abs(35) returns the value 35

abs(-75.38) returns the value 75.38

ceil(x)
x is of type double. Returns a value of type double, which is the
smallest integer value that is not less than x.
Example: ceil(56.34) returns the value 57.0

exp(x)
x is of type double. Returns ex, where e is approximately
2.7182818284590455.
Example: exp(3) returns the value 20.085536923187668

floor(x)
x is of type double. Returns a value of type double, which is the
largest integer value less than x.
Example: floor(65.78) returns the value 65.0

log(x)
x is of type double. Returns a value of type double, which is the
natural logarithm (base e) of x.
Example: log(2) returns the value 0.6931471805599453

log10(x)
x is of type double. Returns a value of type double, which is the
common logarithm (base 10) of x.
Example: log10(2) returns the value 0.3010299956639812

max(x, y)
Returns the larger of x and y. If x and y are of type int, it returns a
value of type int; if x and y are of type long, it returns a value of type
long; if x and y are of type float, it returns a value of type float;
if x and y are of type double, it returns a value of type double.
Example: max(15, 25) returns the value 25

max(23.67, 14.28) returns the value 23.67

max(45, 23.78) returns the value 45.00

min(x, y)
Returns the smaller of x and y. If x and y are of type int, it returns a
value of type int; if x and y are of type long, it returns a value of type
long; if x and y are of type float, it returns a value of type float;
if x and y are of type double, it returns a value of type double.
Example: min(15, 25) returns the value 15

min(23.67, 14.28) returns the value 14.28

min(12, 34.78) returns the value 12.00

pow(x, y)
x and y are of type double. Returns a value of type double, which is xy.
Example: pow(2.0, 3.0) returns the value 8.0

pow(4, 0.5) returns the value 2.0

round(x)
Returns a value which is the integer closest to x.
Example: round(24.56) returns the value 25

round(18.35) returns the value 18