View Single Post
  #2 (permalink)  
Old 12-29-2007, 11:46 AM
tim's Avatar
tim tim is offline
Senior Member
 
Join Date: Dec 2007
Location: South Africa
Posts: 334
tim is on a distinguished road
Using Math.random() and text files.
Hi!. Here's a method that will read a text file:
Code:
public static Vector<String> loadFile(String filename){ Vector<String> strings = new Vector<String>(); try{ FileReader file = new FileReader(filename); BufferedReader buffer = new BufferedReader(file); while (true) { String line = buffer.readLine(); if (line == null) break; else { strings.add(line); } } buffer.close(); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } return strings; }
Using this method and Math.random(), you can access random lines in your text file. Lets assume that each question is on a separate line in the text file. Your main() method could look like this.
Code:
public static void main(String[] arguments){ Vector<String> data = loadFile("questions.txt"); int pos = (int)((double)data.size() * Math.random()); System.out.println("Next question: " + data.get(pos)); }
Remember to add the imports:
Code:
import java.io.*; import java.util.*;
My code has been checked by hand, so just scream if there is a problem.
__________________
If your ship has not come in yet then build a lighthouse.
Reply With Quote