Introduction:
In this program, we aim to create a simple Java application that displays a random quote from a predefined list of quotes. This type of program helps to learn basic Java programming concepts such as working with arrays, using the Random class, and displaying output to the user.
Objective:
The objective of this exercise is to demonstrate how to implement randomness in Java. Specifically, the program will randomly select one quote from an array of quotes and display it each time it is executed.
Code:
// RandomQuote.java import java.util.Random; public class RandomQuote { public static void main(String[] args) { // Array of quotes String[] quotes = { "The only way to do great work is to love what you do. - Steve Jobs", "Life is what happens when you're busy making other plans. - John Lennon", "To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment. - Ralph Waldo Emerson", "In the end, it's not the years in your life that count. It's the life in your years. - Abraham Lincoln", "Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill" }; // Create a Random object Random random = new Random(); // Generate a random index to select a quote int randomIndex = random.nextInt(quotes.length); // Display the randomly selected quote System.out.println("Random Quote: "); System.out.println(quotes[randomIndex]); } }
Explanation of Program Structure:
The program consists of the following parts:
- Import Statement: We import the
Random
class fromjava.util
package to generate random numbers. - Array of Quotes: The program stores a list of quotes in a String array. Each quote is a string element in the array.
- Random Object: A
Random
object is created to generate random numbers. - Random Index: The
nextInt()
method of theRandom
class is used to generate a random index between 0 and the length of the quotes array. - Output: The randomly selected quote is displayed to the user using
System.out.println()
.
How to Run the Program:
- Step 1: Open your preferred Java development environment (IDE) or text editor.
- Step 2: Create a new file and save it as
RandomQuote.java
. - Step 3: Copy and paste the provided code into your file.
- Step 4: Compile the program by running the following command in your terminal or IDE:
javac RandomQuote.java
- Step 5: Run the compiled program with the command:
java RandomQuote
- Step 6: You should see a randomly selected quote displayed on the console each time you run the program.