Download Java Methods, Classes and Object Oriented

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Methods, Classes and Object Oriented Development
Review of Basic concepts
1. Describe two reasons for using Java as a
programming language.
2. Describe the following two main data types
available in Java .
(i) Primitive data
(ii)abstract Data type(Reference/Object)
3. Define the term Object.
4. An application is more flexible when values can be
read from an _____________. An input stream is the
__________________ received from an
input device, such as a keyboard. For example, as a
user types data, the data goes into the input stream.
To process data in the input stream, Java includes the
Scanner class with methods for reading integers,
floating point numbers, and strings.
A program that obtains a value from the user must
instantiate a __________object that is initialized with an
input stream. For data typed from a
keyboard, initialize the object with
____________because it represents the standard input
stream.
5. (i)________________A data type that represents true
or false.
(ii)_______________ A data type that represents a
single character.
(iii) __________double A data type that represents
positive or negative floating point numbers.
(iv) ___________ Keyword used to declare an identifier
a constant.
Generating Random Numbers
A widely used method for generating random
numbers is called the Linear Congruential Method. This
method uses a formula to generate a sequence of
numbers. Although the numbers in the sequence vary
and for most applications can be considered
random,the sequence will at some point repeat.
Therefore, random numbers in a
computer application are referred to as pseudorandom
(like random).
Java includes the Random class in the java.util
package for generating random numbers. This class
uses the Linear Congruential Method. Some
of the Random class methods include:
Class Random (java.util.Random)
Methods
nextInt() returns the next random integer in the random
number generator’s sequence.
nextInt(int n) returns the next random integer between 0
(inclusive) and n in the random number generator’s
sequence.
nextDouble() returns the next random double between 0.0
and 1.0 in the random number generator’s
sequence.
The RandomNumberDemo class below instantiates a
Random object and displays the first five numbers
between 0 and 100 in its sequence:
public class RandomNumberDemo {
public static void main(String[] args) {
Random r = new Random();
System.out.println("First number: " + r.nextInt(100));
System.out.println("Second number: " + r.nextInt(100));
System.out.println("Third number: " + r.nextInt(100));
System.out.println("Fourth number: " + r.nextInt(100));
System.out.println("Fifth number: " + r.nextInt(100));
}
}
To generate a random number in a range with a
minimum value greater than 0, the following formula is
used:
r.nextInt(highNum - lowNum + 1) + lowNum
A similar formula can be used to generate random
doubles in a range:
(highNum - lowNum + 1) * r.nextDouble() + lowNum
Java provides a built-in class called String
ingTokenizer that parses strings and breaks them into
tokens. To use it, you have to import it from java.util.
In its simplest form, the StringTokenizer uses spaces to
mark the boundaries between tokens. A character that
marks a boundary is called a delimiter.
We can create a StringTokenizer in the usual way, passing as an
argument the string we want to parse.
StringTokenizer st = new StringTokenizer ("Here
are four tokens.");
The following loop is a standard idiom for extracting the tokens from
a StringTokenizer.
while (st.hasMoreTokens ()) {
System.out.println (st.nextToken());
}
StringTokenizer st = new StringTokenizer ("11
22+33*", " +-*/", true);
6. Describe the term top-down design.
Top-down development and procedural abstraction
were used to break the program specification down into
levels of subtasks, as shown on the
below. Outlining the levels of subtasks in pseudocode
defines a main() method and two other methods:
main()
Prompt the user for the conversion type.
Execute the appropriate method to convert the temperature.
fahrenheitToCelsius()
Prompt the user for a temperature in degrees Fahrenheit
Convert the temperature to degrees Celsius
Display the temperature
celsiusToFahrenheit()
Prompt the user for a temperature in degrees Celsius
Convert the temperature to degrees Fahrenheit
Display the temperature
The application:
import java.util.Scanner;
public class TempConverter {
public static void fahrenheitToCelsius() {
double fTemp, cTemp;
1
By: Gayani Gupta-CS1050-Class Work ------09-25-2013----------------------------------------------------------------Page
Scanner input = new S canner(System.in);
System.out.print("Enter a Fahrenheit temperature: ");
fTemp = input.nextDouble();
input.close();
cTemp = (double)5/(double)9*(fTemp - 32);
System.out.println("The Celsius temperature is " + cTemp);
}
public static void celsiusToFahrenheit() {
double cTemp, fTemp;
Scanner input = new Scanner(System.in);
System.out.print("Enter a Celsius temperature: ");
cTemp = input.nextDouble();
input.close();
fTemp = (double)9/(double)5*cTemp + 32;
Sys te m.out.pr i ntl n("T he Fa h r e n heit te m p er atu r e is "
+ fTemp);
}
public static void main(String[] args) {
int choice;
Scanner input = new Scanner(System.in);
/* Prompt user for type of conversion */
System.out.println("1. Fahrenheit to Celsius conversion.");
System.out.println("2. Celsius to Fahrenheit conversion.");
System.out.print("Enter your choice: ");
choice = input.nextInt();
if (choice == 1) {
fahrenheitToCelsius();
} else {
celsiusToFahrenheit();
}
input.close();
}
}
A method consists of a declaration and a body. The
method declaration includes access level, return type,
name, and parameters, if any. The method
body contains the statements that implement the
method
7. What does the word static means in the above class
methods?
8. Write a method with parameter to print the following
output.
What is the purpose of the Return Statement in a
method?
A method can return a value. The return statement is
used to send a value back to the calling statement.A
return statement can return only one value.
The return Statement
A method can return a value. For example, the
cubeOf() method returns the cube of its parameter:
public static double cubeOf(double x) {
double xCubed;
xCubed = x * x * x;
return(xCubed);
}
 The return statement is used to send a value



back to the calling statement.
A return statement can return only one value.
A method declared as void does not contain a
return statement.
A method that returns a value is called from a
statement that will make use of the returned
value, such as an expression or an assignment
/**
* Calculates the cube of a number.
* pre: none
* post: x cubed returned
*/
public class CubeCalculator {
public static double cubeOf(double x) {
double xCubed;
xCubed = x * x * x;
return(xCubed);
}
public static void main(String[] args) {
double num = 2.0;
double cube;
cube = cubeOf(num);
System.out.println(cube);
}
}
Method documentation is in the form of
documentation comments (/** */) that appear just above
the method declaration. For example, the drawBar()
method with documentation:
9. Modify the above method to have an int parameter
for the length of the bar and a String parameter for
the character to use to draw the bar:
/**
* Print a bar of asterisks across the screen.
* pre: length > 0
* post: Bar drawn of length characters, insertion
* point moved to next line.
*/
public static void drawBar(int length, String mark) {
for (int i = 1; i <= length; i++) {
System.out.print(mark);
}
System.out.println();
}
What is Method Overloading?
10. Write a method declaration for each of the following
descriptions:
a) A class method named getVowels that can be
called by any other method, requires a String
parameter, and returns an integer value.
b) A class method named extractDigit that can
be called by any other method, requires an
integer parameter, and returns an integer
value.
c) A class method named insertString that can
be called by any other method, requires a
String parameter and an integer parameter,
and returns a String parameter
when more than one method of the same name is
included in a class.
2
By: Gayani Gupta-CS1050-Class Work ------09-25-2013----------------------------------------------------------------Page