University of Toronto -- Department of Computer Science CSC 108S - Spring 1998 Midterm test (Clarke's section) Aids allowed: Textbook only. Time: 50 minutes Question 1 Solution. [10 marks] ------------------------------- import java.io.*; public class A { public static void main (String[] args) throws IOException { DataInputStream in = new DataInputStream (System.in); String mostLine = ""; int mostCount = 0; final String stopper = "XXX"; String line = in.readLine(); while (!line.equals(stopper)) { int count = 0; for (int i = 0; i < line.length(); i++) if (line.charAt(i) == 'J') count++; if (count > mostCount) { mostCount = count; mostLine = line; } line = in.readLine(); } if (mostCount >= 0) // includes the case where "the most J's" is zero J's. System.out.println (mostLine); else System.out.println ("No input!"); } } OR HERE IS ANOTHER SOLUTION TO QUESTION 1: import java.io.*; public class A { public static void main (String[] args) throws IOException { DataInputStream in = new DataInputStream (System.in); String mostLine = ""; int mostCount = 0; final String stopper = "XXX"; while (true) { String line = in.readLine(); if (line.equals(stopper)) break; int count = 0; for (int i = 0; i < line.length(); i++) if (line.charAt(i) == 'J') count++; if (count > mostCount) { mostCount = count; mostLine = line; } } if (mostCount >= 0) // includes the case where "the most J's" is zero J's. System.out.println (mostLine); else System.out.println ("No input!"); } } Question 2 Solution. [10 marks] ------------------------------- import java.io.*; class Prof { private String name; private int age; public Prof (String name, int age) { this.name = name; this.age = age; } public boolean olderThan (Prof otherProf) { return age > otherProf.age; // You don't need to say "this.age", but it's OK. And you don't need // a getAge() method to access the otherProf's age, but it's OK to // use one, if you write it. } public String getName() { return name; } } public class B { public static void main (String[] args) throws IOException { DataInputStream stdin = new DataInputStream (System.in); // The previous three lines are not required as part of the test answer. // Create the first Prof. String name = stdin.readLine(); int age = Integer.parseInt(stdin.readLine()); Prof p1 = new Prof(name,age); // Create the second Prof. name = stdin.readLine(); age = Integer.parseInt(stdin.readLine()); Prof p2 = new Prof(name,age); // Compare them and print the result. if (p1.olderThan(p2)) System.out.println (p1.getName() + " is older than " + p2.getName()); else System.out.println (p1.getName() + " is older than " + p1.getName()); } }