Professional Documents
Culture Documents
Module-3-Selections-and-LoopsUpdated
Module-3-Selections-and-LoopsUpdated
Module-3-Selections-and-LoopsUpdated
Event-Driven
Programming
Event-Driven Programming | 1
Republic of the Philippines
Romblon State University
Romblon, Philippines
LEARNING OUTCOMES:
ABSTRACTION
3. 2 System.currentTimeMillis()
The java.lang.System.currentTimeMillis() method returns the current time in milliseconds. The unit
of time of the return value is a millisecond, the granularity of the value depends on the underlying
operating system and may be larger.
Examples:
package javaActivities;
import java.util.Scanner;
public class AdditionQuiz {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.println( number1 + " + " + number2 + " = " + answer + " is " +
(number1 + number2 == answer));
}
}
SAMPLE OUTPUT:
Event-Driven Programming | 2
Republic of the Philippines
Romblon State University
Romblon, Philippines
3. 3 Math.random()
The java.lang.Math.random( ) 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.
Examples:
package javaActivities;
import java.util.Scanner;
public class SubtractionQuiz {
SAMPLE OUTPUT:
Event-Driven Programming | 3
Republic of the Philippines
Romblon State University
Romblon, Philippines
3. 4 Loops
A loop can be used to tell a program to execute statements repeatedly.
Suppose you need to display a string (e.g., Welcome to Java!) a hundred times. It would be tedious
to have to write the following statement a hundred times:
package javaActivities;
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
}
}
The variable count is initially 0. The loop checks whether count < 100 is true. If so, it executes the loop body
to display the message Welcome to Java! and increments count by 1. It repeatedly executes the loop body until count
< 100 becomes false. When count < 100 is false (i.e., when count reaches 100), the loop terminates, and the next
statement after the loop statement is executed.
Loops are constructs that control repeated executions of a block of statements. The concept of looping is
fundamental to programming. Java provides three types of loop statements: while loops, do-while loops, and for
loops.
Event-Driven Programming | 4
Republic of the Philippines
Romblon State University
Romblon, Philippines
Example #1:
package javaActivities;
import java.util.Scanner;
public class AdditionQuizV2 {
// Create a Scanner
Scanner input = new Scanner(System.in);
System.out.print(
"What is " + number1 + " + " + number2 + "? ");
int answer = input.nextInt();
SAMPLE OUTPUT:
Event-Driven Programming | 5
Republic of the Philippines
Romblon State University
Romblon, Philippines
package javaActivities;
import java.util.Scanner;
public class SubtractionQuizLoop {
Event-Driven Programming | 6