/* new topics: inheritance exceptions io xml socket io */ import java.io.*; import java.net.*; /* introduce idea of inheritance explain carefully meaning of public, private, protected hidden vars */ class team { protected int wins, losses; public void win() { wins++; } public void lose() { losses++; } public int gamesplayed() { return wins + losses; } } class footballteam extends team { private String quarterback; public footballteam(String q) { quarterback = q; wins = losses = 0; } } class hockeyteam extends team { private String goalie; private int ties; // can have ties in hockey public void tie() { ties++; } public hockeyteam(String g) { goalie = g; ties = wins = losses = 0; } // an overriding method: public int gamesplayed() { return wins + losses + ties; } } // hockeyteam // team footballteam as a team - can use footballteam whenever a team // (superclass object is expected). // ---------- Exceptions: -- handle events that can't be anticipated. // --- use carefully - avoid them if you can. public class nov17 { public static int largest(int[] A) throws Exception { if (A==null || A.length==0) throw new Exception("empty array!"); int ax; int i = 0; ax = A[0]; // array could be empty! while (iax) ax=A[i]; i++; } // while return ax; } public static void main(String[] args) { int[] A = new int[10]; int x; try { x = largest(A); System.out.println(x); // Write to a file: PrintWriter pw; FileOutputStream fs = new FileOutputStream("test.dat"); pw = new PrintWriter(new OutputStreamWriter(fs)); pw.println("hello"); pw.println("there"); pw.close(); // read from a file: BufferedReader br; FileInputStream ins = new FileInputStream("test.dat"); br = new BufferedReader(new InputStreamReader(ins)); // while loop to print each line in file: String a = br.readLine(); while (a != null) { System.out.println("read " + a+" from file"); a = br.readLine(); } br.close(); //web server ServerSocket sfd; Socket cfd; sfd = new ServerSocket(8888); sfd.setReuseAddress(true); cfd = sfd.accept(); // cfd = new Socket("www.cs.hofstra.edu",80); System.out.println("connection established"); br = new BufferedReader (new InputStreamReader(cfd.getInputStream())); pw = new PrintWriter (new OutputStreamWriter(cfd.getOutputStream())); a = br.readLine(); // get request pw.print("HTTP/1.1 200 OK\r\n"); pw.flush(); pw.print(" \n"); pw.print("

Welcome to my homepage

\n"); pw.print(" \n\r\n"); pw.flush(); br.close(); pw.close(); cfd.close(); sfd.close(); } catch (Exception e) // e is a parameter {System.out.println(e); System.exit(0);} } }