Create a "quote of the day" program. The program should read in the contents of a file containing at least 10 quotes. The program must read the quotes from the file into an array, and then randomly print one of them to the screen.
To create the text file, use Notepad or another text editor and place each quotation on a separate line. Make sure your text file is part of your project. You should also attach a seperate copy of the text file into the dropbox in case there are any issues.
import java.io.*;
import java.util.*;
import java.lang.StringBuilder;
import java.math.*;
public class FileReader{
public static void main(String args[]) {
try(FileInputStream fin = new FileInputStream("../uploads/QuoteOfTheDay.txt"))
{
ArrayList listOfQuoteOfTheDay = new ArrayList();
StringBuilder sb = new StringBuilder();
int quotesCounter = 0;
int i=-1;
while((i=fin.read())!=-1){
if((char)i == '"'){
quotesCounter++;
if(quotesCounter == 2){
listOfQuoteOfTheDay.add(sb.toString());
sb = new StringBuilder();
quotesCounter = 0;
}
}else{
sb.append((char) i);
}
}
double randomQuoteOfTheDay = Math.random() * listOfQuoteOfTheDay.size();
int parseInt = (int)Math.round(randomQuoteOfTheDay);
System.out.println(listOfQuoteOfTheDay.get(parseInt));
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
}
Comments
Leave a comment