In: Computer Science
Before you begin your program: Create a text file in your project folder with 20 "quirky sayings"/fortunes (the only requirement is that they be appropriate for display in class), In your program you will Create a list by reading those 20 fortunes from your file Ask the user how many fortunes he/she wants to see. store the value in a variable Inside of a loop (loop as many times as the user asked) select a random answer from your list of fortunes wait for the user to press the enter key (the easy way is to use the Scanner's nextLine method) Note that it is quite possible that you will see some fortunes more than once while not seeing some at all.
If you have any problem with the program feel free to comment.
Program
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String[] args)throws
IOException {
Scanner sc = new
Scanner(System.in);//for taking console input
//for reading file data
BufferedReader br = new
BufferedReader(new FileReader("data.txt"));
String line;
int count=0;
String[] fortunes = new
String[20];
//reading and storing file data to
fortunes[]
while ((line = br.readLine()) !=
null) {
fortunes[count]
= line;
count++;
}
System.out.print("Enter the number
of fortunes: ");
int size = sc.nextInt();
sc.nextLine();//taking user input and flushing scanner object
int random;
System.out.println("*********Your
Fortunes*********");
for(int i=0; i<size; i++)
{
random =
(int)(Math.random()*20);//generating random value
System.out.println(fortunes[random]);//showing the fortunes
sc.nextLine();//waiting for user to press enter
}
//closing the resources
sc.close();
br.close();
}
}
data.txt
Output