// Eric Jewart // Sample code for CPS 1, Lab 7 // 10 October 1997 package awb; import java.util.*; import java.io.*; import java.net.*; public class Database extends Object { // data members (don't change these): protected Questionnaire[] data; // all the Questionnaires in the database protected int size; // the number of Questionnaires protected final int MAX_SIZE = 500; // capacity of database protected String status; // status of database // constructor (don't change this) public Database() { data = new Questionnaire[MAX_SIZE]; // create array size = 0; // 0 Questionnaires in array } public Questionnaire getQuestionnaire(int index) { return data[index]; } // This function reads the available data into // the array. Do not modify this function. You // are not required to understand the Java used in // this function (but ask Eric or Steve if you're // curious). public void initData(String link) { try { URL u = new URL(link); URLConnection uc = u.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); StringTokenizer stok; double year; String gender; String area; String party; String reg; String vote; double pres[] = new double[4]; double like[] = new double[4]; String line; while ( (line = in.readLine()) != null) { stok = new StringTokenizer(line, "|"); if ( stok.countTokens() != 14 ) continue; year = Double.valueOf(stok.nextToken()).doubleValue(); gender = stok.nextToken(); area = stok.nextToken(); party = stok.nextToken(); reg = stok.nextToken(); vote = stok.nextToken(); for ( int i = 0; i < 4; i++) pres[i] = Double.valueOf(stok.nextToken()).doubleValue(); for ( int i = 0; i < 4; i++) like[i] = Double.valueOf(stok.nextToken()).doubleValue(); data[size++] = new Questionnaire(year, gender, area, party, reg, vote, pres[0], pres[1], pres[2], pres[3], like[0], like[1], like[2], like[3] ); } if (size > 0) status = "okay"; else status = "no elements found in data file"; } catch (MalformedURLException ex) { status = "data file not found"; } catch (IOException ex) { status = "cannot read data file"; } } // This function is used by the applet to make sure the // database is okay. Do not modify it. public String checkStatus() { return status; } // This function returns the size of the database. It is // used by the DBApplet to display info on the screen. public int getSize() { return size; } public static void main (String[] args){ Database db = new Database(); db.initData("http://www.duke.edu/~bier/awb/election-survey.db"); int size = db.getSize(); Questionnaire q; for ( int i=0; i< size; i++ ) { q = db.getQuestionnaire(i); System.out.println( q.getYear()+" "+ q.getGender()+" "+q.getArea()+" "+ q.getParty()+" "+q.getReg()+" "+q.getVote()+" "+ q.getPresidentRating(0)+" "+q.getPresidentRating(1)+" "+ q.getPresidentRating(2)+" "+q.getPresidentRating(3)+" "+ q.getPersonRating(0)+" "+q.getPersonRating(1)+" "+ q.getPersonRating(2)+" "+q.getPersonRating(3)); } } }