Programming 12

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Republic of the Philippines

Department of Education
N a t i o n a l C a pi t a l Re g i o n
Sc h o o l s D i v i s i o n O f f i c e o f La s Pi ñ a s C i t y

NAME: ________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
FOURTH QUARTER
WEEK 1

MOST ESSENTIAL LEARNING COMPETENCY

• Demonstrate using decision constructs in accordance with Java


framework. TLE_ICTJAVA11-12POAD-IIf-i-29

t OBJECTIVES

1. Demonstrate the use of If Statement.


2. Demonstrate the use of If-Else Statement.

PRE-TEST: Multiple Choice (10 points)

Directions: Read each item carefully and choose the correct answer.

1. What kind of statement is an if statement?


A. a conditional statement C. an anecdotal statement
B. a comparison statement D. all of the above

2. What kind of operators do if statements use to test conditions?


A. arithmetic operators C. comparison operators
B. array operators D. none of the above

3. What happens when an if statements conditional is not true?


A. nothing happens C. the if statement starts over
B. the if statement executes D. all of the above

2
4. Which of the following control expressions are valid for an if statement?
A. a Boolean expression C. either A or B
B. an integer expression D. neither A nor B

5. Which of the following is NOT a comparison operator in Java language??


A. > C. =
B. < D. ==

SELECTION/DECISION CONSTRUCTS

The control statements that allow alternative actions based upon


conditions that are evaluated at run time are called selection statements.

THE IF STATEMENT

The if statement allows for conditional execution. The statement that is


included within it will be executed only if its condition is true. The syntax for the
simple if statement is:

if (condition)
statement;

where condition is a boolean expression and statement is the statement that


will execute if the value of the boolean expression is true. (A boolean expression
is an expression whose value has boolean type: either true or false).

Relational and Equality Operators in Java

The equality and relational operators determine if one operand is greater


than, less than, equal to, or not equal to another operand. A relational operator
determines whether a specific relationship exists between two values and
equality operator determines whether two values are equal.

3
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

Boolean Expressions using Relational Operators

Expression Meaning
x>y Is x greater than y?
x<y Is x less than y?
x >= y Is x greater than or equal to y?
x <= y Is x less than or equal to y?
x == y Is x equal to y?
x != y Is x not equal to y?

The following program asks the user to enter grades of a student for two
semesters and calculates the average grade. If the grade is greater than or equal
to 90, the program displays “With Honors! Congratulations!”

import java.util.Scanner; //Scanner class

//program that demonstrates the if statement


public class AverageGrade
{
public static void main(String[] args)
{
double grade1, // first sem grade
grade2, // second sem grade
average; // average grade

// create a Scanner object to read input.


Scanner input = new Scanner(System.in);

System.out.println("This program averages "


+ "2 semester grades.");

4
// get the first sem grade.
System.out.print("Enter first sem grade: ");
grade1 = input.nextDouble();

// get the second sem grade.


System.out.print("Enter second sem grade: ");
grade2 = input.nextDouble ();

// calculate and display the average grade.


average = (grade1 + grade2) / 2.0;
System.out.println("The average is " + average);

// if the average is greater than or equal to 90


// program displays “With Honors! Congratulations!”
if (average >= 90)
System.out.println("With Honors! Congratulations!");
}
}

Program Output 1:

This program averages 2 semester grades.


Enter first sem grade: 85
Enter second sem grade: 88
The average is 86.5

Program Output 2:

This program averages 2 semester grades.


Enter first sem grade: 93
Enter second sem grade: 92
The average is 92.5 Flowchart of an if statement
With Honors! Congratulations!

5
Flowchart of an if statement

True
average
>= 90

False Display “With


Honors!”

Sample if statements
Statement Result
if (sales > 10000) if sales is more than 10000, the
commission = 1000; commission variable is assigned
with 1000.

if (x != 0) if x is not equal to 0, product is


product = product * x; multiplied by x and new value is
saved in product replacing the old
value.

if (value < 1) if value is less than 1, message


System.out.println(“invalid number”); “invalid number” is displayed.

THE IF-ELSE STATEMENT

The if-else statement is the if statement with an added else clause. It works
the same way as the if statement except that, when the condition is false, the
statement within the else clause executes. The syntax for the if-else statement
is:

6
if (condition)
statement;
else
statement;

Division y zero is undefined. The following program asks the user to enter
two numbers, dividend and divisor. The program will display an error message
“Division by zero is undefined!” if divisor is equal to zero else the program will
display the quotient.

import java.util.Scanner; // needed for the Scanner class

//program demonstrate the if-else statement


public class DivisionZero
{
public static void main(String[] args)
{
int xnumber, ynumber; // two numbers
double quotient; // quotient of two numbers

//create a Scanner object to read input.


Scanner input = new Scanner(System.in);

//get two numbers from the user.


System.out.print("Enter a number [dividend]: ");
xnumber = input.nextInt();
System.out.print("Enter another number [divisor]: ");
ynumber = input.nextInt();

//determine whether division by zero will occur.


if (ynumber == 0)
{
//division by zero error message
System.out.println("Division by zero is undefined!");
System.out.println("Enter a non-zero divisor.");
}
else
{
//perform division and display quotient
quotient = (double) xnumber / ynumber;

7
System.out.print("The quotient of " + xnumber);
System.out.print(" and " + ynumber);
System.out.println(" is " + quotient);
}
}
}

Program Output 1:

Enter a number [dividend]: 7


Enter another number [divisor]: 5
The quotient of 7 and 5 is 1.4

Program Output 2:

Enter a number [dividend]: 9


Enter another number [divisor]: 0
Division by zero is undefined!
Enter a non-zero divisor.

Flowchart of an if-else statement

True
divisor
!= 0

False Display “The


quotient is: ”

Display
“Division by
zero is
undefined!”

8
POST-TEST Multiple Choice (10 points)
Direction: Read each item carefully and choose the correct answer.

1. The if statement is an example of which of the following?


A. class structure C. pathway structure
B. decision structure D. sequence structure

2. Which of the following type of expression has a value of either true or


false?
A. Boolean expression C. decision expression
B. binary expression D. unconditional expression

3. What is an empty statement that does nothing?


A. conditional statement C. null statement
B. missing statement D. virtual statement

4. Which of the following you enclose the statements with, when creating a
block of statements?
A. angled brackets < > C. parentheses ( )
B. braces { } D. square brackets [ ]

5. How does the character “A” compare to the character “B”?


A. “A” is equal to “B” C. “A” is less than “B”
B. “A” is greater less than “B” D. You cannot compare characters.

9
NAME: _________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
FOURTH QUARTER
WEEK 2

MOST ESSENTIAL LEARNING COMPETENCY

• Demonstrate using decision constructs in accordance with Java


framework. TLE_ICTJAVA11-12POAD-IIf-i-29

OBJECTIVES

1. Demonstrate the use of Nested-If Statement.


2. Demonstrate the use of If-Else-If Statement.

PRE-TEST MULTIPLE CHOICE (10 points)

Direction: Read each item carefully and choose the correct answer.

1. What is a structure consisting of a sequence of statements enclosed in


braces, functioning as if it were a single statement?
A. compound statement C. conditional expression
B. condition D. branch

2. What decision structure works best if you have more than two possible
answers (multiple choice) to a question, and those answers can be
integer or character based?
A. an if statement C. a switch statement
B. an if-else statement D. nested-if statements

3. Which of the following, the condition of an if statement evaluates to


boolean if the expression contains?
A. Boolean operands C. relational operators
B. logical operators D. all of the above

10
4. Which of these are selection statements in Java?
A. break C. for( )
B. continue D. if( )

5. Which is the not equal relational operator?


A. < C. !=
B. > D. ==

NESTED IF STATEMENTS

A nested-if statement occurs when the true or false statement of an if


statement is itself an if statement. a nested-if statement can be used to
implement decisions with several alternatives.

The following algorithm is an application of a nested-if statement of a salary


loan application program. The program will process a salary loan application if
the applicant satisfies two conditions: 1.) salary of an applicant is at least 15,000
per month; 2.) residency of the applicant is at least 3 years in the company.

False Display “Salary should be


salary >= at least 15000 a month to
15000 qualify.”

True

False
residency Display “Residency should
>= 3 be at least 3 years to
qualify.”

True

Display “You qualify


for a salary loan!”

11
A Java program that demonstrates a nested-if statement.

import java.util.Scanner;

/**
* This program demonstrates a nested if statement.
*/

public class SalaryLoan


{
public static void main(String[] args)
{
double salary; // Applicant’s monthly salary
double residency; // Applicant’s years of residency

// Create a Scanner object for keyboard input.


Scanner input = new Scanner(System.in);

// Get the applicant’s monthly salary.


System.out.print("Enter your monthly salary: ");
salary = input.nextDouble();

// Get the applicant’s years of residency.


System.out.print("Enter your years "
+ "of residency: ");
residency = input.nextDouble();

// Determine whether an applicant qualifies for a salary loan.


if (salary >= 15000)
{
if (residency >= 3)
{
System.out.println("You qualify for a salary loan.");
}
else
{
System.out.println("Residency "
+ "should be at least "
+ "3 years to qualify.");
}

12
}
else
{
System.out.println("Salary should be at least "
+ "15,000 a month to qualify.");
}
}
}

Program Output 1:

Enter your monthly salary: 16000


Enter your years of residency: 2
Residency should be at least 3 years to qualify.

Program Output 2:

Enter your monthly salary: 12000


Enter your years of residency: 6
Salary should be at least 15,000 a month to qualify.

Program Output 3:

Enter your monthly salary: 17000


Enter your years of residency: 4
You qualify for a salary loan.

THE IF-ELSE-IF STATEMENT

The if-else-if statement tests a series of conditions. It is used to decide


among three or more actions. The following is the general format of an if-else-
if statement:

if(condition1)
{
//block of code to be executed if condition1 is true.
}

13
else if(condition2)
{
//block of code to be executed if condition1 is false and condition2
is true
}

else
{
//block of code to be executed if condition1 is false and condition2
is false
}

IF-ELSE-IF PROBLEM

average

YES
average “Distinction.”
>= 95

NO

YES
average “Merit.”
>= 90

NO

YES
average “Completer.”
>= 75

NO

“Incomplete.”

14
The problem demonstrates the if-else-if statement. The above algorithm asks
the user to enter final average grade of a student and displays the equivalent
worded grade.

Numeric Grade Worded Grade


95 and above Distinction
90 - 94 Merit
75 - 89 Completer
Below 75 Incomplete

A Java program that demonstrates an if-else-if statement.

import java.util.Scanner;

//This program demonstrates an if-else-if statement.

public class HonorsGrade


{
public static void main(String[] args)
{
double average; // Student final grade

// Create a Scanner object for keyboard input.


Scanner input = new Scanner(System.in);

// Get the student's final grade.


System.out.print("Enter your grade: ");
average = input.nextDouble();

// Determine student performance.


if (average >= 95)
System.out.println("Congratulations! You got Distinction mark!");

else if (average >= 90)


System.out.println("Congratulations! You got Merit mark!");

else if (average >= 75)


System.out.println("Congratulations! Completer.");

else
System.out.println("Incomplete.");
}
}

15
Program Output 1:

Enter your grade: 92


Congratulations! You got Merit mark!

Program Output 2:

Enter your grade: 76


Congratulations! Completer!

A Java program that demonstrates an if-else-if statement. the program asks


the user to enter a number and program displays whether it is positive,
negative or zero.

import java.util.Scanner;

public class PosNeg


{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

System.out.print("Enter a number: ");


int number = input.nextInt();

if(number > 0)
{
System.out.println("Number is positive.");
}

else if(number < 0)


{
System.out.println("Number is negative.");
}

else
{
System.out.println("Number is zero.");
}
}
}

16
Program Output 1:

Enter a number: -4
Number is negative.

Program Output 2:

Enter a number: 0
Number is zero.

POST-TEST MULTIPLE CHOICE (10 points)

Direction: Read each item carefully and choose the correct answer.

1. What operators determine whether a specific relationship exists between


two values?
A. arithmetic operators C. logical operators
B. combination operators D. relational operators

2. What executes statements only when a certain condition is met?


A. decision structure C. logical structure
B. execution structure D. sequence structure

3. What is enclosing one structure inside of another?


A. inserting C. nesting
B. looping D. zoning

4. What operators either change the value of a boolean expression or


combine two boolean expressions?
A. arithmetic operators C. logical operators
B. combination operators D. relational operators

5. What type of expression is either true or false?


A. arithmetic expression C. initialization expression
B. Boolean expression D. loop expression

17
NAME: _________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
FOURTH QUARTER
WEEK 3

MOST ESSENTIAL LEARNING COMPETENCY

• Demonstrate using decision constructs in accordance with Java


framework. TLE_ICTJAVA11-12POAD-IIf-i-29

OBJECTIVES

1. Demonstrate the use of Logical Operators.


2. Demonstrate the use of Logical Operators in IF Statements.

PRE-TEST MULTIPLE CHOICE (10 points)

Direction: Read each item carefully and choose the correct answer.

1. What operators either change the value of a boolean expression or


combine two boolean expressions?
A. arithmetic operators C. logical operators
B. combination operators D. relational operators

2. Which of the following is the logical AND operator?


A. && C. ==
B. || D. &

3. Which of the following operators has the highest precedence?


A. - C. =
B. != D. /

18
4. Which results in true if both conditions are true?
A. AND C. OR
B. NOT D. NOR

5. Which results in true if one condition is true?


A. AND C. OR
B. NOT D. NOR

LOGICAL OPERATORS

Logical operators in Java combine boolean expression to form compound


boolean expressions, just as arithmetic operators +, -, *, / and % combine
arithmetic expressions to form compound arithmetic expressions. The “and”
symbol && is one of the logical operators used in Java programs. The other two
are || for “or” and ! for “not”.

Logical Operators
Operator Meaning Effect
&& AND Combines two boolean expressions into one
compound expression. Both boolean expressions
must be true to have a true result.
|| OR Combines two boolean expressions. To have a true
result, any of the two boolean expressions must be
true.
! NOT The ! “not” reverses the truth of the boolean
expression.

Boolean Expressions using Logical Operators


Expression Meaning
m < n && a > b Is m less than n AND a greater than b?
a == b || a == c Is a equal to b OR a equal to c?
!(a == b) Is the expression a equal to b NOT true?

The && Operator is called the logical AND. It combines two boolean
expressions and will only have a true result if both boolean expressions are
true. Here is an example of an if statement that uses && logical AND operator:

19
if (temperature < -10 && minutes > 15)
{
System.out.println("The temperature is in the danger zone!");
}

Truth Table for Logical AND Operator


Expression Result
true && false false
false && true false
false && false false
true && true true

Sample Problem:

The program will process a salary loan application if the applicant satisfies
BOTH conditions: 1.) salary of an applicant is at least 15,000 per month; AND
2.) residency of the applicant is at least 3 years in the company.

import java.util.Scanner;

//This program demonstrates logical AND.

public class LogicalAnd


{
public static void main(String[] args)
{
double salary; // Applicant's monthly salary
double residency; // Applicant's years of residency

// Create a Scanner object for keyboard input.


Scanner input = new Scanner(System.in);

// Get the applicant's monthly salary.


System.out.print("Enter your monthly salary: ");
salary = input.nextDouble();

// Get the applicant's years of residency.


System.out.print("Enter your years "
+ "of residency: ");

20
residency = input.nextDouble();

// Determine whether the user qualifies for the loan.


if (salary >= 15000 && residency >= 3)
{
System.out.println("You qualify for a salary loan.");
}
else
{
System.out.println("You do not qualify for a salary loan.");
}
}
}

Program Output 1:

Enter your monthly salary: 17000


Enter your years of residency: 2
You do not qualify for a salary loan.

Program Output 2:

Enter your monthly salary: 13000


Enter your years of residency: 6
You do not qualify for a salary loan.

Program Output 3:

Enter your monthly salary: 18000


Enter your years of residency: 4
You qualify for a salary loan.

The || Operator is called the logical OR. It combines two boolean


expressions and will only have a true result if any of the two boolean
expressions is true. Here is an example of an if statement that uses || logical
OR operator:

21
if (temperature < -10 || temperature > 45)
{
System.out.println("The temperature is in the danger zone!");
}

Truth Table for Logical OR Operator


Expression Result
true || false true
false || true true
false || false false
true || true true

Sample Problem:

The program will process a salary loan application if the applicant satisfies
ANY of the two conditions: 1.) salary of an applicant is at least 15,000 per month;
OR 2.) residency of the applicant is at least 3 years in the company.

import java.util.Scanner;

//This program demonstrates logical OR.

public class LogicalOr


{
public static void main(String[] args)
{
double salary; // Applicant's monthly salary
double residency; // Applicant's years of residency

// Create a Scanner object for keyboard input.


Scanner input = new Scanner(System.in);

// Get the applicant's monthly salary.


System.out.print("Enter your monthly salary: ");
salary = input.nextDouble();

// Get the applicant's years of residency.


System.out.print("Enter your years "
+ "of residency: ");
residency = input.nextDouble();

22
// Determine whether the user qualifies for the loan.
if (salary >= 15000 || residency >= 3)
{
System.out.println("You qualify for a salary loan!");
}
else
{
System.out.println("You do not qualify for a salary loan!");
}
}
}

Program Output 1:

Enter your monthly salary: 18000


Enter your years of residency: 2
You qualify for a salary loan.

Program Output 2:

Enter your monthly salary: 11000


Enter your years of residency: 5
You qualify for a salary loan.

Program Output 3:

Enter your monthly salary: 13000


Enter your years of residency: 2
You do not qualify for a salary loan.

The ! Operator is called the logical NOT. The NOT reverses the truth of the
boolean expression. If the expression is true, the ! operator returns false. If the
expression is false, the ! operator returns true. It is a unary operator that
reverses the logical value of a boolean expression which is its operand. Here is
an example of an if statement that uses ! logical NOT operator:

23
if (!(temperature > 45))
System.out.println("This is below the highest temperature.");

Truth Table for Logical NOT Operator


Expression Result
! true false
! false true

Order of Precedence of Operators


Order of Operators Description
Precedence
1 -! Unary Negation, Logical Not
2 */% Multiplication, Division, Modulus
3 +- Addition, Subtraction
4 < > <= >= Less than, Greater than, Less than or equal
to, Greater than or equal to
5 == != Equal to, Not equal to
6 && Logical AND
7 || Logical OR
8 = += -= *= /= Assignment and Combined assignment
%=

Logical Operators in Order of Precedence


!
&&
||

24
POST-TEST MULTIPLE CHOICE (10 points)

Direction: Read each item carefully and choose the correct answer.

1. Which Java logical operator checks either values are true, but not both?
A. AND C. NOT
B. OR D. XOR

2. Which of the following is the logical NOT operator?


A. && C. ==
B. || D. !

3. Consider the following inputs: c = 5; b = 8; d = 3. What does the following


expression return? (c < b) OR (b < d)
A. true C. 3
B. false D. invalid

4. Consider the following inputs: c = 5; b = 8; d = 3. What does the following


expression return? (c < b) AND (b < d)
A. true C. 3
B. false D. invalid

5. AND, OR, NOT are examples of what operators?


A. arithmetic operators C. logical operators
B. combination operators D. relational operators

25
NAME: _________________________________________ DATE: ________________

GRADE & SECTION: ___________________________ TEACHER: _____________

MODULE IN PROGRAMMING NC III


GRADE 12
FOURTH QUARTER
WEEK 4

MOST ESSENTIAL LEARNING COMPETENCY

• Demonstrate using decision constructs in accordance with Java


framework. TLE_ICTJAVA11-12POAD-IIf-i-29

OBJECTIVES

1. Demonstrate the use of Switch Statement.


2. Demonstrate the use of Random Class.

PRE-TEST MULTIPLE CHOICE (10 points)

Direction: Read each item carefully and choose the correct answer.

1. What is a part of a switch statement that will execute if there are no


values that matched the given choices?
A. break C. default
B. case D. none of the above

2. What is the data type that can be used in switch statement?


A. array data type C. double data type
B. char data type D. float data type

3. What is a java keyword used in switch statements that causes immediate


exit or that terminates the switch statement?
A. the break keyword C. the default keyword
B. the case keyword D. the switch keyword

4. What control statement is a switch in Java?


A. loop C. iteration
B. jump D. selection

26
5. What type of data a switch statement accepts as input?
A. byte C. short
B. int D. all of the above

THE SWITCH STATEMENT

The switch statement is like the if-else-if combination for processing one of a
set of alternatives. Use the switch statement to use one of many code blocks to
be executed.

This is how it works:

• The switch expression is evaluated once.


• The value of the expression is compared with the values of each case.
• The expression is a variable or an expression that gives a char, byte,
short, int or string value.
• If there is a match, the associated block of code is executed.
• The break and default keywords are optional.

When Java reaches a break keyword, it breaks out of the switch block. This
will stop the execution of more code and case testing inside the block.
The default keyword specifies some code to run if there is no case match. It is
used at the last statement in a switch block.

General Format of a Switch Statement

switch (expression)
{
case x:
//code block
break;
case y:
//code block
break;
default:
//code block
}

27
A Java program that demonstrates how Switch Statement works.

import java.util.Scanner; // Needed for the Scanner class


//This program demonstrates the switch statement.

public class SwitchDemo


{
public static void main(String[] args)
{
String input; // To hold keyboard input
char choice; // To store the user's choice

// Create a Scanner object to read input.


Scanner myKeyboard = new Scanner(System.in);

// Ask the user to enter A, B, or C.


System.out.print("Enter A, B, or C: ");
input = myKeyboard.nextLine();
choice = input.charAt(0); // Get the first char

// Determine which character the user entered.


switch (choice)
{
case 'A':
System.out.println("You entered A.");
break;
case 'B':
System.out.println("You entered B.");
break;
case 'C':
System.out.println("You entered C.");
break;
default:
System.out.println("That's not A, B, or C!");
}
}
}

Program Output 1:

Enter A, B or C: A
You entered A.
28
Program Output 2:

Enter A, B or C: E
That is not A, B, or C!

Without the break statement, after a match is made, all of the


statements further down the switch are executed until a break or end of
the switch is found. Sometimes this may be needed in the program. Here is
a Java program that enters the age of a person and displays if eligible to
vote. This program demonstrates the above explanation.

import java.util.Scanner;

public class SwitchBreakDemo


{
public static void main(String[] args)
{
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter Age: ");
age = inputDevice.nextInt();
switch (age)
{
case 10:
case 15:
case 17:
System.out.println("You are not eligible for voting");
break;
case 18:
System.out.println("You are eligible for voting");
}
}
}

Program Output 1:

Please enter age: 15


You are not eligible for voting.

Program Output 2:

Please enter age: 18


You are eligible for voting. 29
A switch expression can be a char, byte, short, or int value. With Java 7
onwards, expression can also be a string. Here is a program that
demonstrates a switch with a string expression. The program ask the user
to enter weekday and translates it to Tagalog version.

import java.util.Scanner;

/*This program translates English weekdays to


Tagalog words version.*/

public class Tagalog


{
public static void main(String[] args)
{
String input;

// Create a Scanner object to read input


Scanner mykeyboard = new Scanner(System.in);

// Get a day from the user.


System.out.print("Enter day of the week: ");
input = mykeyboard.nextLine();

// Translates the English weekdays to Tagalog version.


switch (input)
{
case "friday":
System.out.println("byernes");
break;
case "saturday":
System.out.println("sabado");
break;
case "sunday":
System.out.println("linggo");
break;
case "monday":
System.out.println("lunes");
break;
case "winter":
System.out.println("el invierno");
break;

30
default:
System.out.println("Please enter one of these words:\n"
+ "friday, saturday, sunday, monday");
}
}
}

RANDOM NUMBERS

There are many applications that feature random numbers generation such
as Statistics applications that generates random numbers for sample data
analysis. Java provides ways to generate random numbers using some built-in
methods and classes such as: java.util.Random class; Math.random method is
used to return a pseudorandom double type number greater than or equal to 0.0
and less than 1.0. The default random number always generated between 0 and
1.

The class Random is part of the java.util package, so that any program that
uses it will need an import statement such as: import java.util.Random;

To create an object with a variable name randomNumbers from the Random


class, the general format is:

Random randomNumbers = new Random();

This declares a variable named randomNumbers from the Random class. The
new Random() creates an instance of the Random class and the equal sign
assigns the address of the Random class to the randomNumbers variable. After
the statement executes, the randomNumbers variable references a Random
object and may now invoke methods such as nextInt(), nextDouble(),
nextLong() using that instance.

Some of the Random class methods


Method Description
nextDouble() Returns the next random number as a double and number
will be within the range of 0.0 and 1.0.
nextInt() Returns the next random number as an int and number will
be within the range of an int, which is 22,147,483,648 to
12,147,483,647.
nextInt(int n) This method accepts an integer argument, n. It returns a
random number as an int and number will be within the
range of 0 and, not including n.

31
// A Java program to demonstrate random number generation
// using java.util.Random;
import java.util.Random;

public class GenerateRandomNumbers


{
public static void main(String args[])
{
// create instance of Random class
Random rand = new Random();

// Generate random integers in range 0 to 999


int rand_int1 = rand.nextInt(1000);
int rand_int2 = rand.nextInt(1000);

// Print random integers


System.out.println("Random Integers: "+rand_int1);
System.out.println("Random Integers: "+rand_int2);

//Generate Random doubles


double rand_dub1 = rand.nextDouble();
double rand_dub2 = rand.nextDouble();

// Print random doubles


System.out.println("Random Doubles: "+rand_dub1);
System.out.println("Random Doubles: "+rand_dub2);
}
}

POST-TEST: Multiple Choice (10 points)


Direction: Read each item carefully and choose the correct answer.

1. Which class is used to generate random number?


A. java.lang.object C. java.util.Random
B. java.util.randomNumber D. java.util.Object

2. Which method is used to generate boolean random values in java?


A. nextBoolean() C. previousboolean()
B. generateBoolean() D. randomboolean()

32
3. What is the return type of Math.random() method?
A. boolean C. integer
B. double D. String

4. What is the range of numbers returned by Math.random() method??


A. -1.0 to 1.0 C. 0 to 100
B. -1 to 1 D. 0.0 to 1.0

5. Which method is used to generate double random values in java?


A. nextDouble() C. previousDouble()
B. generateDouble() D. randomDouble()

ANSWER KEY TO PRE-TESTS AND POST-TESTS

5. D 5. A 5. C 5. C 5. C 5. B 5. C 5. A
4. D 4. D 4. A 4. B 4. D 4. C 4. A 4. B
3. A 3. B 3. D 3. A 3. C 3. C 3. A 3. C
2. B 2. A 2. A 2. D 2. C 2. D 2. C 2. A
1. C 1. C 1. C 1. B 1. A 1. D 1. A 1. B
Pretest Posttest Pretest Posttest Pretest Posttest Pretest Posttest
Week4 Week3 Week2 Week1

REFERENCES:

• Deitel, P. & Deitel, H. (2012). Java How to Program. 9th Edition

• Brown, B. (2005). A Guide to Programming Java. 5 th Edition

• Gaddis, T. (2015). Starting-Out with Java. 5th Edition

• Downey, A. & Mayfield, C. (2016). Think Java. 1 st Edition

• Hubbard, J. (2004). Programming with Java. 2 nd Edition

• W3Schools Online Web Tutorials. (2021). [online] Available at:


<https://www.w3schools.com/>

33

You might also like