Showing posts with label test. Show all posts
Showing posts with label test. Show all posts

Monday, April 30, 2012

Final Tests

These are the final tests. If you want your graded final just send me an email and I will tell you when I'll be in my office so you can pick it up.

  1. (10%) Implement a method that prints out all the numbers between 1 and 10,000,000 except that if the number is a multiple of 3 you will print "GO", if it is a multiple of 7 you print "Cocky" and if its a multiple of both 3 and 7 you print "Go Gamecocks". That is, the first part of the output looks like
    1
    2
    GO
    4
    5
    GO
    Cocky
    8
    GO
    10
    11
    GO
    13
    Cocky
    GO
    16
    17
    GO
    19
    20
    Go Gamecocks
    22
    ...and so on...
  2. (10%) Implement the method int add(String a, String b) (notice, a and b are String) which adds the two arguments and returns the sum, but only if the two are integers. If they are not then it returns 0. For example
    add("5", "3") //returns 8
    add("bob", "3")  //returns 0
    add("bob", "alice")  //returns 0
    add("1.456", "8")  //returns 0
                
  3. (10%) Implement a method String myCode(boolean[] msg) which translates the boolean array into a string using the following
    code:
    true → E
    false true → T
    false false true → A
    false false false → b
    For example,
    boolean[] m1 = {true};
            System.out.println(myCode(m1)); //prints "E"
    
            boolean[] m2 = {false, true, false, false, false};
            System.out.println(myCode(m2)); // "Tb"
    
            boolean[] m3 = {true, false, false, true, false, false, false};
            System.out.println(myCode(m3)); // "EAb"
    
            boolean[] m4 = {false, false, false, false, false, false, false, true};
            System.out.println(myCode(m4)); // "bbT"
                
  4. (10%) Given that you have
    public enum SmartPhone {iphone3g, iphone4, iphone4s, android};
              
    Implement a method that takes SmartPhone as an argument and returns its price, as given by the following table

    ItemPrice
    iphone 3g300
    iphone 4349
    iphone 4s400
    android200
  5. (10%) What does the following program printout?
    public class PrintoutExceptions {
    
        public static String xkcd(int x) throws Exception{
            if (x < 0){
                return "Magnets";
            }
            else if (x < 5){
                return "Sticks";
            }
            else if (x % 2 == 1){
                return "Number:" + Integer.toString(x);
            }
            else throw new Exception("Caramba");
        }
    
    
        public static void main(String[] args) {
    
            int[] a = {-5,0,1,3,7,8};
            for (int i = 0; i < a.length; i++) {
                try {
                    System.out.println(i + "-" +  xkcd( a[i] ));
                } catch (Exception e) {
                    System.out.println("Ooops");
                }
            }
        }
    }
  6. (10%) Does the program below run or crash? If it runs, show what it prints out when it runs. If it crashes, explain why.
    public class A {
    
        public String toString() {
            return "I am A";
        }
    }
    
    public class B extends A {
    
        public String toString() {
            return "I am B";
        }
    }
    
    public class C extends A {
    
        public String toString(){
            return "I am C";
        }
    }
    
    public class Q6 {
    
        public static void main(String[] args) {
            A[] as = new A[3];
            as[0] = new A();
            as[1] = new B();
            as[2] = new C();
            for (A a : as) {
                System.out.println(a.toString());
            }
        }
    } 
  7. (10%) Given the following code:
    public class Person {
    
        private int money;
    
        private Person[] friends;
    
        public int minDistanceToMillionaire(){
            //TODO: implement this method
        }
    }
    implement the missing method using recursion, which will return the distance to the closest millionaire. For example, if the person is a millionaire (has money >= 1,000,000) then it will return 0. Otherwise, if the person has a friend who is a millionaire then it will return 1. Otherwise, if the person has a friend who has a friend that is a millionaire then it will return 2, and so on.
    You can assume that the graph does not have loops in it. That is, you will never see the same Person twice.


  8. (10%) Assume that you are given a class called Person which has a method called int distanceTo(Person other) that returns the distance between where this person lives and where other lives.
    Implement a method
    ArrayList<Person> hasFriendsCloserThan(HashMap<Person, HashSet<Person>> socialNet, int n) 
    that takes as input a socialNet, which is a mapping between a Person and his friends, and returns the list of all the people who have at least one friend that lives a distance of less than n away from them.


The other test:

  1. (10%)Implement a method that returns the sum of all the odd numbers between 1 and 1,000,000 except that those that are multiples of both 3 and 5 count double, while those that are multiples of either just 3 or just 3 don't get counted. For example, if the sum was just between 1 and 20 then you would return 98 because that is the sum of 1 + 7 + 11 + 13 + (15*2) + 17 + 19.
  2. (10%) Implement a method int ssnToInt(String ssn) which, when given a a String represenation of a social security number that looks like "123-45-6789" returns the integer that represents that number, namely 123456789. If given a String that does not match then it returns -1. Specifically,
    ssnToInt("123-45-6789") //returns 123456789
    ssnToInt("123456789") //returns -1
    ssnToInt("12304506789") //returns -1
    ssnToInt("12389") //returns -1
    ssnToInt("7aa-90-879B") //returns -1
            
  3. (10%) Implement a method String compress(String dna) which takes as input a String that contains only the characters A,C,G, and T, and then compresses the string by counting how many times each one appears consecutively. If a character appears more than once in a row the whole sequence is replaced by the character followed by the number of times it appeared in a row. For example:
    String d1 = "ACGT";
            System.out.println(compress(d1)); //prints ACGT
    
            String d2 = "AAAAACGT";
            System.out.println(compress(d2)); //prints A5CGT
    
            String d3 = "CCCTTTTAGGGGG";
            System.out.println(compress(d3)); //prints C3T4AG5
    
            String d4 = "AAAAAA";
            System.out.println(compress(d4)); //prints A6
                
  4. (10%) Given that you have
    public enum Tablet {ipad, ipad2, newipad, galaxy}; 
    Implement a method that takes a SmartPhone and returns its price, as given by the following table

    ItemPrice
    ipad300
    ipad2400
    newipad600
    galaxy300

  5. (10%) What does the following program printout?
    public class PrintoutExceptions {
    
        public static String onion(int x) throws Exception{
            if (x % 2 == 1){
                return "Carrot";
            }
            else if (x <= 0){
                return "Sticks";
            }
            else if (x < 5){
                return "Number:" + Integer.toString(x);
            }
            else throw new Exception("Caramba");
        }
    
    
        public static void main(String[] args) {
    
            int[] a = {-5,0,1,3,7,8};
            for (int i = 0; i < a.length; i++) {
                try {
                    System.out.println(i + "-" +  onion( a[i] ));
                } catch (Exception e) {
                    System.out.println("Ooops");
                }
            }
        }
    }
  6. (10%) Does the program below run or crash? If it runs, show what it prints out when it runs. If it crashes, explain why.
    public class A {
    
        public String toString() {
            return "I am A";
        }
    }
    
    public class B extends A {
    
        public String toString() {
            return "I am B";
        }
    }
    
    public class C extends A {
    
        public String toString(){
            return "I am C";
        }
    }
    
    public class Q6 {
        static void foo(A a){
            System.out.println(a.toString());
        }
    
        public static void main(String[] args) {
            foo(new A());
            foo(new B());
            foo(new C());
        }
    } 
  7. (10%) Given the following code:
    public class Person {
    
        private Person mother;
    
        private Person father;
    
        public int generationsToOldestKnownAncestor(){
            //TODO: implement this method
        }
    
    }
    implement the missing method using recursion, which will return the distance to the oldest known ancestor. If we don't know a Person's mother or father we set those properties to null. For example, if a Person has both mother and father as null then the method should return 0. But, if the person has only a mother, who in turn has both mother and father set to null then it should return 1, and so on.
    You can assume that the graph does not have loops in it. That is, you will never see the same Person twice.

  8. (10%) Implement the method
    String topPerson(HashMap<String, ArrayList<Double>> gradeMap)
    which takes as input a gradeMap, which is a mapping from a student's name to his list of grades, and which returns the name of the student with the highest grade. For example, if Alice has grades of 10, 20, 88, and Bob has grades of 77, 55, then it would return Alice because of her 88.

Final Test Point Distribution

The final test point distribution is below, these are points not grades. You will receive the actual grade along with your class grade in an email that I have just sent.




Wednesday, April 18, 2012

Test 3 Points Distribution

The points distribution for Test 3 is below. These are points, not grades. I will talk about grades in class.



Monday, April 16, 2012

Test 3

Here are the two tests, with some sample solutions.
  1. (25%) What does the following program print out when run?
    public class Q1 {
    public static boolean swing (int strength) throws Exception{ if (strength < 5) throw new Exception("Too weak"); if (strength > 10) return false; return true; }
    public static void main(String[] args) { int[] strengths = {5,6,-1,12}; for (int s : strengths) { try { if (swing(s)) System.out.println("Homerun"); else System.out.println("Strike!"); } catch (RuntimeException e){ System.out.println("You are OUT!"); } catch (Exception e) { System.out.println(e.getMessage()); } } System.out.println("Done."); } }

  2. (25%)Given a text file called sales.txt which contains data that looks like
    aba 55.99
    akdkd8dj 12.95
    iwjwhe 4
    Iji8keJl 44.99
    ijdddawe 10.00
    ...and so on for many more rows...
    
    where each row represents one item that is for sale in a store. The first column is a String that uniquely identifies the item and the second column is a double that represents the price of the item. Write a program which


    1. Implements a simple Item class that can represent one item.
    2. In the main, your program reads the complete contents of the file sales.txt into an ArrayList<Item> variable called items.
    Answer:
    public class Item {
        private String sku;
    
        private double price;
    
        public Item(String sku, double price){
            this.sku = sku;
            this.price = price;
        }
    
        public String toString(){
            return sku + " " + price;
        }
        public static void main(String[] args) {
            try {
                Scanner in = new Scanner(new FileInputStream("sales.txt"));
                ArrayList<Item> items = new ArrayList<Item>();
                while (in.hasNext()){
                    String sku = in.next();
                    double price = in.nextDouble();
                    items.add(new Item(sku,price));
                }
                System.out.println(items);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
       }
    } 
  3. (25%) Read over the code below and implement the empty method.
    import java.util.ArrayList;
    
    public class Q3 {
    
        private ArrayList<Q3> data;
    
        private Integer number;
    
        public Q3(Integer number){
            data = new ArrayList<Q3>();
            this.number = number;
        }
    
        public void add(Q3 q){
            data.add(q);
        }
    
        public void add(Integer number){
            data.add(new Q3(number));
        }
        
        /**
         * Calculates and returns the sum of all even numbers in
         * this object or in any of the ones in 'data', and so on
         * recursively.
         * @return The sum.
         */
        public int sumEven(){
            //TODO: implement this method
            int result = 0;
            if (number % 2 == 0)
                result = number;
            for (Q3 q: data){
                result += q.sumEven();
            }
            return result;
        }
        
    
        public static void main(String[] args) {
            Q3 q = new Q3(0);
            Q3 first = new Q3(1);
            q.add(first);
            Q3 second = new Q3(2);
            q.add(second);
            q.add(3);
            q.add(4);
            first.add(8);
            second.add(5); 
            System.out.println(q.sumEven());
        }
    }
    For example, when the main above is run it should print out
    14
  4. (25%) Implement a method String mostFrequent(String s) which returns the 3-character substring that appears most frequently in s, or one of the most frequent if there is a tie. For example
    mostFrequent("AABABA") returns "ABA" because "ABA" appears twice
    mostFrequent("AAAAAB") returns "AAA" because it appears 3 times
    mostFrequent("ATATATA") returns "ATA" because it appears 3 times
                
    Answer:
    public static String mostFrequent(String seq){
            HashMap<String, Integer> count = new HashMap<String, Integer>();
            int max = 0;
            String maxKey = null;
            //add them all
            for (int i = 0; i <= seq.length() - 3; i++) {
                String key = seq.substring(i,i+3);
                if (count.containsKey(key))
                    count.put(key, count.get(key) + 1);
                else
                    count.put(key, 1);
                if (count.get(key) > max){
                    max = count.get(key);
                    maxKey = key;
                }
            }
            return maxKey;
        }



And, the other one:


  1. (25%) What does the following program print out when run?

    public class Q1 {
    public static boolean pitch (String type) throws Exception { if (type.startsWith("f")) return true; if (type.startsWith("c")) return false; if (type.startsWith("x")) throw new Exception("Oops"); return true; }
    public static void main(String[] args) { String[] types = {"fast", "foo", "curve", "xoom"}; for (String t : types) { try { if (pitch(t)) System.out.println("Hit"); else System.out.println("Miss"); } catch (RuntimeException e){ System.out.println("You hit the umpire"); } catch (Exception e) { System.out.println(e.getMessage()); } } System.out.println("Done."); } }

  2. (25%) Given a text file called points.txt which contains data that looks like
    1.44 5.666
    12.999 0
    9.163 3.1415
    6 7
    5 6.999
    ...and so on for many more rows...
    
    where each row represents the x and y coordinates of a point in 2-dimensional space. Both columns are doubles. Write a program which


    1. Implements a simple Point class that can represent one point in space.
    2. In the main, your program reads the complete contents of the file points.txt into an ArrayList<Point> variable called points.
    Answer:
    public class Point {
    
        private double x;
        private double y;
        public Point(double x, double y){
            this.x = x;
            this.y = y;
        }
        public String toString(){
            return "(" + x + "," + y + ")";
        }
        public static void main(String[] args) {
            try {
                Scanner in = new Scanner(new FileInputStream("points.txt"));
                ArrayList<Point> points = new ArrayList<Point>();
                while (in.hasNext()){
                    double x= in.nextDouble();
                    double y = in.nextDouble();
                    points.add(new Point(x,y));
                }
                System.out.println(points);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
  3. (25%) Read over the code below and implement the empty method.
    import java.util.ArrayList;
    
    public class Q3 {
    
        private ArrayList<Q3> data;
    
        private Integer number;
    
        public Q3(Integer number){
            data = new ArrayList<Q3>();
            this.number = number;
        }
    
        public void add(Q3 q){
            data.add(q);
        }
    
        public void add(Integer number){
            data.add(new Q3(number));
        }
    
        
        /**
         * Find if x is either equal to number, or equal to one of
         * the numbers in 'data', and so on recursively.
         * @param x the number we are looking for
         * @return true if x is there, false otherwise.
         */
        public boolean find(Integer x){
            //TODO: implement this method
            if (number == x)
                return true;
            for (Q3 q : data) {
                if (q.find(x))
                    return true;
            }
            return false;
        }
    
        public static void main(String[] args) {
            Q3 q = new Q3(0);
            Q3 first = new Q3(1);
            q.add(first);
            Q3 second = new Q3(2);
            q.add(second);
            q.add(3);
            q.add(4);
            first.add(8);
            second.add(5); 
            System.out.println(q.find(3));
            System.out.println(q.find(5));
            System.out.println(q.find(10));
        }
    }
    For example, when the main above is run it should print
    out
    true
    true
    false
  4. (25%) Implement a method String mostPoints(String[] name, int[] points) which returns the name that has the most points, assuming that for all indeces i we have that points[i] has the number of points for name[i]. For example
       String[] name1 = {"a", "b", "c", "a", "b", "a"};
       int[] points1 =  { 1,   2,   7,   4 ,  3,   1};
       mostPoints(name1, points1); //returns "c" because it has 7
       // points and "a" has 6, and "b" has 5.
    
       String[] name2 = {"a", "b", "c", "a", "b", "a"};
       int[] points2 =  { 5,   2,   7,   4 ,  3,   1};
       mostPoints(name2, points2); //returns "a"
    
       String[] name3 = {"a", "a", "a", "a", "b", "c"};
       int[] points3 =  { 1,   1,   1,   1 ,  3,   2};
       mostPoints(name3, points3); //returns "a"
    Answer:
    public static String mostPoints(String[] name, int[] points){
            HashMap<String, Integer> count = new HashMap<String, Integer>();
            int max = 0;
            String maxKey = null;
    
            for (int i = 0; i < points.length; i++) {
                if (count.containsKey(name[i]))
                    count.put(name[i], points[i] + count.get(name[i]));
                else
                    count.put(name[i], points[i]);
                if (count.get(name[i]) > max){
                    max = count.get(name[i]);
                    maxKey = name[i];
                }
            }
            return maxKey;
        }

Thursday, March 15, 2012

Test 2 and Lab Test 2

Here are the Test 2s and the answers:

  1. (25%) What does the following program print out when run?

    public class Boat extends Ship {
    
     private int seaWorthinessRating;
    
     public Boat(double maxSpeed) {
      super(maxSpeed);
      seaWorthinessRating = 33;
     }
    
     public Boat(double maxSpeed, int rating) {
      super(maxSpeed);
      seaWorthinessRating = rating;
     }
    
     public String toString(){
      return "mp=" + maxSpeed + " seaworth=" + seaWorthinessRating;
     }
    
    }
    
    public class SailBoat extends Boat {
    
      public String toString(){
        return "Sailboat";
      }
    }
    
    public class Ship {
    
     protected double maxSpeed;
    
     public Ship(double maxSpeed){
      this.maxSpeed = maxSpeed;
     }
    
     public String toString(){
      return "maxSpeed="  + maxSpeed;
     }
    
     public static void main(String[] args){
      Ship s1 = new Ship(1);
      System.out.println(s1);
      Ship s2 = new Boat(2,66);
      Ship s22 = new Boat(8);
      System.out.println(s2);
      System.out.println(s22);
      SailBoat s3 = new SailBoat(3,77);
      System.out.println(s3);
      Ship s4 = (Ship)s3;
      System.out.println(s4);
     }
    }

  2. (25%) What is wrong with the program below? Explain.
    public interface Drinkable {
     public void drink();
    
     public boolean isEmpty(){ return false;}
    }
    
    public class RedBull implements Drinkable {
    
     private int size;
    
     public RedBull(int size){
      this.size = size;
     }
    
     public void drink(){
      System.out.println("Yuuuuuckkkkk");
     }
    
     public boolean isEmpty(){
      return true;
     }
    
    }
    Answer: An interface cannot implement a method.
  3. (25%) Implement a static method which takes as an argument an array of integers a and returns a new array, lets call it r, where r[0] has the sum of a[0] + a[1], and r[1] has the sum of a[2] + a[3], and so on. You can assume that the length of a is even.
  4. Answer:
    public static int[] everyOther(int[] a){
      int[] result = new int[a.length/2];
      for (int i = 0; i < a.length; i+=2) {
       result[i/2] = a[i] + a[i+1];
      }
      return result;
     }
            
  5. (25%) Take a look at this code:
    public class Plant {
    
     private String name;
    
     public Plant(String name){
      this.name = name;
     }
    
     public String getName(){
      return name;
     }
    
     public static void main(String[] args){
      Plant[] garden = new Plant[3];
      garden[0] = new Plant("Vine");
      //Create a Rosemary plant with the name Vanity
      // it will have 1024 leaves by default
      garden[1] = new Rosemary("Vanity");
      //This one will have 2048 leaves
      garden[2] = new Rosemary("Pride", 2048);
    
      for (Plant p: garden){
       System.out.println(p.getName()); //print their names
      }
      //getRosemaries() returns the total number of rosemaries
      //  that have been created.
      System.out.println("There are " + Rosemary.getNumRosemaries()
        + " rosemary plants.");
    
      Rosemary r = new Rosemary("Loathing");
      System.out.println(r.getName());
      System.out.println("There are " + Rosemary.getNumRosemaries()
        + " rosemary plants.");
    
     }
    }
            
    Implement the missing Rosemary class so that when we run the code above it will print:
    Vine
    Rosemary:Vanity numLeaves=1024
    Rosemary:Pride numLeaves=2048
    There are 2 rosemary plants.
    Rosemary:Loathing numLeaves=1024
    There are 3 rosemary plants.

    See the comments in the code for hints on what the various
    methods and attributes Rosemary must have.

    Answer:

    public class Rosemary extends Plant {
    
     private int numLeaves;
    
     private static int numCreated = 0;
    
     public Rosemary(String name) {
      super("Rosemary:" + name );
      numLeaves = 1024;
      numCreated++;
     }
    
     public Rosemary(String name, int numLeaves) {
      super("Rosemary:" + name );
      this.numLeaves= numLeaves;
      numCreated++;
     }
    
     public String getName(){
      return super.getName() + " numLeaves=" + numLeaves;
     }
    
     public static int getNumRosemaries(){
      return numCreated;
     }
    
    
    }
and the other one
  1. (25%) What does the following program print out when run?

    public class Boot extends Shoe {
    
     protected int height;
    
     public Boot(int height){
      super(9);
      this.height = height;
     }
    
     public Boot(int height, int size){
      super(size);
      this.height = height;
     }
    }
    
    public class Ugg extends Boot {
    
     public Ugg(int height, int size) {
      super(height,size);
      height--;
     }
    
     public String toString(){
      return "Ugg size=" + super.toString() + " height=" + height;
     }
    }
    public class Shoe {
    
     private int size;
    
     public Shoe(){
      size = 7;
     }
    
     public Shoe(int size) {
      this.size = size;
     }
    
     public String toString() {
      return "Shoe [size=" + size + "]";
     }
    
     public static void main(String[] args) {
      Shoe s1 = new Shoe();
      System.out.println(s1);
      Boot s3 = new Ugg(7,9);
      System.out.println(s3);
      Boot s4 = new Boot(5,15);
      System.out.println(s4);
      Ugg s5 = new Ugg(9,16);
      System.out.println(s5);
      Boot s6 = (Boot)s5;
      System.out.println(s6);
     }
    }

  2. (25%) What is wrong with the program below? Explain.
    public interface Playable{
    
     public void play() {
      super();
     };
    
     public int timeLeft();
    }
    
    public class Media {
    
     protected String title;
    
     public Media(String title){
      this.title = title;
     }
    }
    
    public class Song extends Media implements Playable{
    
     protected int runningTime;
    
     public Song(String name, int runningTime){
      super(name);
      this.runningTime = runningTime;
     }
    
     public void play(){
      System.out.println("Playing....");
     }
    
     public int timeLeft(){
      return runningTime - 10;
     }
    }
            
    Answer: An interface cannot implement a method.

  3. (25%) Implement a static method which takes as an argument an array of integers a and returns a new array, lets call it r, where r[0] contains the sum of a[0] and a[last index in a], r[1] contains the sum of a[1] and a[last index in a minus 1], and so on. You can assume that the length of a is even.

    Answer:

    public static int[] fold(int[] a){
      int[] result = new int[a.length/2];
      for (int i = 0; i < a.length / 2; i++) {
       result[i] = a[i] + a[a.length - 1 - i];
      }
      return result;
     }
                                        
  4. (25%) Take a look at this code:
    public interface LeafEater {
              public void eatLeaf();
    }
    
    public class Mammal {
    
     protected int numToes;
    
     protected static int count = 0;
    
     public Mammal(){
      numToes = 5;
      count++;
     }
    
     public String toString(){
      return "Mammal with " + numToes + " toes.";
     }
    
     public static void main(String[] args) {
      Mammal[] animals = new Mammal[4];
      animals[0] = new Mammal();
    
      //Creates a giraffe with 8 toes and height of 10.0 feet.
      animals[1] = new Giraffe();
    
      //Creates a giraffe with 5 toes and height of 14.6 feet.
      animals[2] = new Giraffe(14.6);
    
      //Creates a giraffe with 8 toes and height of 10.0 feet.
      animals[3] = new Giraffe();
      for (Mammal m : animals){
       System.out.println(m);
      }
    
      //getCount() returns the number of Mammals that have been created.
      System.out.println("There are " + Giraffe.getCount() + " mammals");
     }
    }

    Implement the missing Giraffe class so that when we run the code above it will print:
    Mammal with 5 toes.
    Mammal with 8 toes.-- Giraffe: 10.0 feet.
    Mammal with 5 toes.-- Giraffe: 14.6 feet.
    Mammal with 8 toes.-- Giraffe: 10.0 feet.
    There are 4 mammals
    See the comments in the code for hints on what the various methods and attributes Giraffe must have.

    Answer:

    public class Giraffe extends Mammal implements LeafEater{
    
     private double height;
    
     public Giraffe(){
      super();
      height = 10;
      numToes = 8;
     }
    
     public Giraffe(double height){
      super();
      this.height = height;
     }
    
     public String toString(){
      return super.toString() + "-- Giraffe: " + height + " feet.";
     }
    
     public static int getCount(){
      return count;
     }
    
     public void eatLeaf() {
      System.out.println("Yummm, leaves are good.");
    
     }
    
    }            
And, here is my solution to the Lab Tests.

Wednesday, February 8, 2012

Test 1 Distribution

I have graded Test 1, below is the points (not grades) distribution. I will talk about grades in class.



Monday, February 6, 2012

Test 1 Solutions

Test 1s, and their solutions. I am not showing the output of the programs. Just paste them into eclipse and run them to see what it does.

This is the test for one of the sections:

  1. (25%) What does the following program print out when run?

    	public static void main(String[] args) {
    		boolean bool = true;
    		int i = 0;
    		for (i=0; i < 5; i++){
    			System.out.println(i);
    			if (bool && (i % 2 == 0) )
    				System.out.println("Ob");
    			else if (i < 3)
    				System.out.println("La");
    			else if (i % 2 == 0 || i > 3 )
    				System.out.println("Di");
    		}
    		System.out.println(i < 10);
    	}
              
  2. (25%) What does the following program print out when run?
    	public static void main(String[] args) {
    		String word = "CCBA";
    		while (word.length() > 0){
    			char c = word.charAt(0);
    			System.out.print(c); //notice: print
    			word = word.substring(1);
    			int x = 0;
    			switch (c) { //watch out for missing breaks!
    				case 'A':
    					x = 4;
    				case 'B':
    					x = 2;
    					break;
    				case 'C':
    					x = 3;
    			};
    			for (int i=0; i < x; i++){
    				System.out.print("*"); //print (NOT println)
    			}
    			System.out.println(""); //move to next line
    		}
    	}
            
  3. (25%) Write a program that asks the user to enter a
    word and then prints YES if the first 3 characters of the word
    are the same as the last 3 characters (and in the same order).
    Otherwise, or if the word has fewer than 3 characters, the
    program prints NO. Some sample runs:
    Enter word:alphabet
    NO
    ---we run the program again---
    Enter word:abalataba
    YES
    ---we run the program again---
    Enter word:javaisjav
    YES
    ---we run the program again---
    Enter word:javaisajv
    NO
    ---we run the program again---
    Enter word:jav
    YES
    ---we run the program again---
    Enter word:b
    NO
              
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter word:");
    		String word = keyboard.next();
    		if (word.length() < 3)
    			System.out.println("NO");
    		else if (word.substring(0,3).equals(word.substring(word.length() - 3))) {
    			System.out.println("YES");
    		}
    		else
    			System.out.println("NO");
    	}
    
  4. (25%) Write a program that ask the user to enter a
    sentence and then prints out that same sentence but with every
    other character turned into its uppercase equivalent. For
    example:
    Enter message:this program is impossible to write
    tHiS PrOgRaM Is iMpOsSiBlE To wRiTe
    ---we run the program again---
    Enter message:fun in the sun
    fUn iN ThE SuN
              
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter message:");
    		String msg = keyboard.nextLine();
    		String result = "";
    		for (int i=0; i < msg.length(); i++){
    			String letter = msg.substring(i,i+1);
    			if (i%2 == 0) {
    				result += letter;
    			}
    			else {
    				result += letter.toUpperCase();
    			}
    		}
    		System.out.println(result);
           }
    
This is the test for the other section.
  1. (25%) What does the following program print out when run?

    	public static void main(String[] args) {
    		int i = 5;
    		int sum = 0;
    		for (i=5; i > 0; i--){
    			System.out.println(i);
    			sum += (i * 2);
    			if (i > 2 && i < 4)
    				System.out.println("Ob");
    			else if (i % 3 > 0)
    				System.out.println("La");
    		}
    		System.out.println(sum);
    	}
              

  2. (25%) What does the following program print out when run?
    	public static void main(String[] args) {
    		String word = "ABCCAB";
    		while (word.length() > 0){
    			char c = word.charAt(0);
    			System.out.print(c); //notice: print
    			word = word.substring(2);
    			int x = 0;
    			switch (c) { //watch out for missing breaks!
    				case 'A':
    					x = 3;
    				case 'B':
    					x = 1;
    					break;
    				case 'C':
    					x = 4;
    			};
    			if (x <= 1)
    				System.out.println(" alan");
    			else if (x <= 3)
    				System.out.println(" turing");
    			else
    				System.out.println(" lives");
    		}
    	}
            
  3. (25%)
    Write a program that asks the user to enter a word. If the
    word has an 'a' in it then the program will print out the letter
    that comes after the first 'a' in the word (from
    left-to-right). If there are no 'a's or if the 'a' is the last
    character in the word then the program will print out
    "OOPS". Below are some sample runs.
    Enter word:eventful
    OOPS
    ---we run the program again---
    Enter word:java
    v
    ---we run the program again---
    Enter word:nova
    OOPS
    ---we run the program again---
    Enter word:animation
    n
    
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter word:");
    		String word = keyboard.next();
    		int aIndex = word.indexOf('a');
    		if (aIndex == -1) {
    			System.out.println("OOPS");
    		} 
    		else if (aIndex == word.length() -1 ){
    			System.out.println("OOPS");
    		}
    		else {
    			System.out.println(word.charAt(aIndex + 1));
    		}
    	}
    
  4. (25%) Write a program that asks the user to enter a
    sentence. The program will then print out the total number of
    times the letter 'a' appears in the sentence, as well as the total number of
    times the two letters 'an' appear (in that order). Below are
    some sample runs.
    Enter message:banana
    Number of As = 3
    Number of ANs = 2
    ---we run the program again---
    Enter message:the music of the night
    Number of As = 0
    Number of ANs = 0
    ---we run the program again---
    Enter message:are you suggesting that coconuts migrate?
    Number of As = 3
    Number of ANs = 0
    
    Answer:
    	public static void main(String[] args) {
    		Scanner keyboard = new Scanner(System.in);
    		System.out.print("Enter message:");
    		String msg = keyboard.nextLine();
    		int numAs =0;
    		int numANs = 0;
    		for (int index = 0; index < msg.length(); index++){
    			if (msg.charAt(index) == 'a') {
    				numAs++;
    				//take advantage of short-circuit evaluation
    				if (index + 1 < msg.length() && msg.charAt(index + 1) == 'n') 
    					numANs++;
    			}
    		}
    		System.out.println("Number of As = " + numAs);
    		System.out.println("Number of ANs = " + numANs);
    	}
    



Saturday, December 11, 2010

Final Grades

I have just sent out the email with your final grades. As I mentioned in class, I gave a break to those who did very well on the final: I bumped them up a grade if they were close to the borderline. The final grade curve is as I described in class. Below is the distribution for the grades on the final test and the class as a whole.

Have a good xmas break! and, keep on programming!

Tuesday, December 7, 2010

Final Test

Below is the final. If you want your graded final (the paper itself) send me an email and I'll tell you when you can drop by and pick it up. I will email everyone their final grades when I'm done grading.

  1. (10%) Implement a method that takes as an argument an integer n and then prints out the sum from 0 to 1, from 0 to 2,..., from 0 to n. For example, if you are given 10 then you will print out:
    1
    3
    6
    10
    15
    21
    28
    36
    45
    55
    
    Answer:
    public static void gauss(int n) {
     int sum = 0;
     for (int i=1; i <= n; i++) {
      sum += i;
      System.out.println(sum);
     }
    }
    
  2. (10%) Given the Player class below:
    public class Player {
     public int strength;
     public int defense;
     public boolean magic;
    }
     
    implement a method public boolean winsAgainst(Player other) which returns true if the player can beat or tie other in a fight, false otherwise. The way you determine who wins in a fight is by following these rules:
    1. If a player has magic and the other player does not then the player with magic wins if his strength + defense is greater than the other player's defense.
    2. If both have magic then the one with the highest defense wins.
    3. If neither has magic then the one with the highest defense + magic wins
    Answer:
    public boolean winsAgainst(Player other) {
     if (magic && other.magic) {
      return defense >= other.defense;
     }
     if (!magic && !other.magic) {
      return (strength + defense) >= (other.defense + other.strength);
     }
     //exactly one of us has magic
     if (magic) { //he does not have magic
      return strength + defense >= other.defense;
     }
     //he has magic, I don't
     return defense >= other.strength + other.defense;
    }
     
  3. (10%) What does the following program print out?
     public static void flurberg(int x) {
      if (x < 0) {
       System.out.println("Turing");
       return;
      }
      try {
       int y = 10 / x;
       System.out.println("VonNeuman");
      }
      catch (ArithmeticException e) { //division by 0 error
       System.out.println("Babbage");
      }
      finally {
       System.out.println("Lovelace");
      }
      
     }
    
     public static void main(String[] args) {
      flurberg(0);
      flurberg(-1);
      flurberg(1);
     }
    
    Answer:
    Babbage
    Lovelace
    Turing
    VonNeuman
    Lovelace    
    
  4. (15%) In this problem you will implement a small class hierarchy to demonstrate that you understand OOP concepts. You will
    1. Implement a class called Present that has a protected property called name, which is a String, and shippingWeight, which is an integer.
    2. Implement a constructor for the Present which takes 2 arguments: name and shippingWeight, and sets the appropriate data members.
    3. Implement a class called BoardGame which extends Present and has a property called numPlayers which is an integer and is protected.
    4. Implement a 2-argument constructor for Boardgame with arguments name and numPlayers. All board games have a shippingWeight = 16. The constructor should call the parent constructor and set all property values appropriatedly.
    5. Implement a class called Clothing which extends Present and has the property size which is a String.
    Answer:
    public class Present {
     protected String name;
     
     /**
      * in ounces
      */
     protected int shippingWeight;
     
     public Present(String name, int shippingWeight) {
      this.name = name;
      this.shippingWeight = shippingWeight;
     }
    }
    public class BoardGame extends Present {
    
     protected int numPlayers;
     
     public BoardGame(String name, int numPlayers) {
      super(name, 16);
      this.numPlayers = numPlayers;
     }
    
    }
    public class Clothing extends Present {
    
     protected String size;
     
     public Clothing(String name, int shippingWeight, String size) {
      super(name,shippingWeight);
      this.size = size;
     }
     
    }
     
  5. (15%) Implement a method that takes as input an array of Strings and returns the number of "sheep" in the array that appear before "zzzzz". For example:
    • Given the array {"sheep", "fox", "sheep", "zzzzz"}, you return 2.
    • Given the array {"fox", "fox", "zzzzz", "sheep"}, you return 0.
    • Given the array {"sheep", "sheep", "sheep", "sheep"}, you return 4.
    Answer:
    public static int countSheepUntilDone(String[] words) {
     int numSheep = 0;
     for (String w : words) {
      if (w.equals("sheep"))
       numSheep++;
      if (w.equals("zzzzz"))
       return numSheep;
     }
     return numSheep;
    }
     
  6. (10%) The program shown below has one, and only one, compile-time error (which prevents this program from compiling). Write down which line has the error and explain why this is an error.
    public class FinalTest {
     
     private String name;
     
     private static int grade;
     
     private static final int numQuestions = 101;
     
     public FinalTest(String name) {
      this.name = name;
      FinalTest.grade = 0;
     }
     
     public String toString() {
      return name + " " + FinalTest.numQuestions;
     }
     
     public static void setName(String name) {
      this.name = name;
     }
    
     public static void main(String[] args) {
      FinalTest NoNewbies = new FinalTest("neo");
      System.out.println(NoNewbies);
      NoNewbies.name = "Trinity";
     }
    }
     
    Answer: The
       public static void setName(String name) {
      this.name = name;
     }
     
    is an error because a static method cannot access instance variables. I also accepted the answer that one could not set .name to "Trinity" because it is private. That answer is wrong because main is a method of FinalTest, but that is a more tricky question than I wanted to ask. I should have made name public.
  7. (15%) The class
    public class Folder {
     public Folder [] subFolders;
     public int numFiles;
    }
    
    represents the folder hierachy in a computer filesystem. Where a folder can contain a number of files (given by numFiles) as well as a number of sub folders (stored in the subFolders) array. You will implement a recursive method for the Folder which returns the total number of files in the folder and all its sub-folders, sub-sub-folders, sub-sub-sub-folders, etc. For example, if the folder has numFiles=5 and has 2 subFolders each with numFiles=2 and no subFolders, then you will return 9 (that is, 5+2+2).
    Answer:
    public int totalFiles() {
     if (subFolders == null || subFolders.length == 0) {
      return numFiles;
     }
     int numFilesSubfolders = 0;
     for (Folder f : subFolders) {
      numFilesSubfolders += f.totalFiles();
     }
     return numFiles + numFilesSubfolders;
    }
     
  8. (15%) Implement the method public static int countRepeats(int[] values) which returns the number of numbers in values that appear more than once. Assume that all numbers in values are in the range 0 to 99 (inclusive). For example:
    • Given the input array values = {4,4,4,4,4,4} you will return 1, as the number 4 is repeated more than once.
    • Given {1,2,3,4,95} you will return 0 as no number is repeated.
    • Given {1,3,3,1,5} you will return 2 as the numbers 1 and 3 are repeated.
    Answer:
    /**
    * Counts the number of items in 'values' that appear more than once in values. 
    * Assume that 0 <= values[x] < 100 
    * @param values
    * @return the number of  
    */
    public static int countRepeats(int[] values) {
     int[] count = new int[100];//all set to 0 by default
     for (int val : values) {
      count[val]++;
     }
     int result = 0;
     for (int val : count) {
      if (val > 1) {
       result++;
      }
     }
     return result;
    }       
     

Tuesday, November 23, 2010

Test 3 Solutions

  1. (20%) Implement a method called isFileThere(String fileName) which returns true if either fileName exists (is the name of a file in the filesystem) or filename.png exists. For example, if the file is "apple" then it should return true if either "apple" or "apple.png" refer to a file in the filesystem. Return false otherwise.
    Answer:
     public static boolean isFileThere(String fileName) {
      File f = new File(fileName);
      if (f.exists()) {
       return true;
      }
      f = new File(fileName + ".png");
      if (f.exists()) {
       return true;
      }
      return false;
     }
     
  2. (20%) What does the following program print out?
    public class Exceptional {
    
     public void happyDays(int x, int y) throws Exception {
      int a[] = {4}; //array with one item.
      try {
       int d = a[x];
       if (y == 0) {
        throw new Exception("Heeeeyyyy");
       }
       System.out.println("Hello Fonzie");
      }
      catch (IndexOutOfBoundsException e) {
       System.out.println("Hello Richie");
      }
     }
    
     public static void main(String[] args) {
      Exceptional e = new Exceptional();
      try {
       e.happyDays(0,1);
       e.happyDays(1,1);
       e.happyDays(0,0);
      } catch (Exception e1) {
       System.out.println("Hello Potsie");
      }
     }
    
    }
    
    Answer: There where three different tests, each with a different answer:
    public static void main(String[] args) {
     Exceptional e = new Exceptional();
     try {
      e.happyDays(0,1);
      e.happyDays(1,1);
      e.happyDays(0,0);
     } catch (Exception e1) {
      System.out.println("Hellow Potsie");
     }
     System.out.println("-------");
     try {
      e.happyDays(1,1);
      e.happyDays(0,1);
      e.happyDays(0,0);
     } catch (Exception e1) {
      System.out.println("Hellow Potsie");
     }
     System.out.println("--------");
     try {
      e.happyDays(1,1);
      e.happyDays(0,0);
      e.happyDays(1,0);
     } catch (Exception e1) {
      System.out.println("Hellow Potsie");
     }
    }
    Hello Fonzie
    Hello Richie
    Hellow Potsie
    -------
    Hello Richie
    Hello Fonzie
    Hellow Potsie
    --------
    Hello Richie
    Hellow Potsie
      
      
  3. (30%) Implement a recursive method that returns the mutant power of a Person. The mutant power of a Person depends on whether or not that person has the X-Gene, and how many of her ancestors have the X-Gene, with maternal lineage being doubly important.
    Specifically, you are given the class
    public class Person {
     public Person mother;
     public Person father;
     /** True if person had the X-Gene */
     public boolean xgene;
    } 
    
    where either mother or father could be null, signifying that no one up that lineage has the X-Gene (ignore them). The mutantPower of a Person Y is given by the formula:
    • mutant-power(Y) = (1 if Y has X-Gene, 0 otherwise) + 2 * mutant-power(Y's mom) + mutant-power(Y's dad).
    Implement int Person.calculateMutantPower(). For example, the code below prints out xavier's mutant power which is 3.
    public static void main(String[] args) {
     Person xavier = new Person();
     xavier.xgene = true;
     Person mom = new Person();
     mom.xgene = true;
     xavier.mother = mom;
     System.out.println(xavier.calculateMutantPower()); // 3
    }
    
    Answer:
    public int calculateMutantPower () {
     int power = (xgene) ? 1 : 0;
     int motherPower = 0;
     int fatherPower = 0;
     //The base case is when both mother and father are null, in which case we just return 1.
     if (mother != null) {
      motherPower = mother.calculateMutantPower();
     }
     if (father != null) {
      fatherPower = father.calculateMutantPower();
     }
     return power + 2*motherPower + fatherPower;
    }
      
  4. (30%) Implement a class called Set which implements a mathematical set, which we define as a bunch of elements of the same type where no element appears more than once (no repeats allowed). You will use an ArrayList to implement your Set.
    The Set will implement 3 methods:
    1. a no-argument constructor (Tip: see Listing 12.10 in your textbook)
    2. an add(...) method which adds a new element to the set, if its not already there,
    3. a toString() method which turns the whole set into a string, with a dash '-' between each element.
    The following is an example usage of the Set class you will write:
    public static void main(String[] args) {
     Set<String> s = new Set<String>();
     s.add("Hi");
     s.add("Hello");
     s.add("Hi");
     s.add("Hi");
     s.add("how are you?");
     System.out.println(s); //prints Hi-Hello-how are you?-
    }
         
    Answer:
    import java.util.ArrayList;
    
    public class Set<T> {
    
     private ArrayList<T> list;
     
     public Set() {
      list = new ArrayList<T>(10); 
     }
     
     public void add(T element) {
      if (!list.contains(element)) {
       list.add(element);
      }
     }
     
     public String toString() {
      String result = "";
      for (int i=0; i < list.size();i++) {
       result += list.get(i) + "-";
      }
      return result;
     }
    }
     

Tuesday, October 26, 2010

Test 2

  1. (20%) Implement a method called determineWinner which takes two integer arrays as parameters. The arrays represent the number of points each team scored in a set of games that the teams played against each other. Your method should print out the name of the team that won the most games, or whether the tournament was a tie. Remember that if both teams score the same number of points in a game then that game is a tie (it is not a win for either team). Below is an example of how your method will be called:
    public class Tournament {
      
      public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8};
        int[] b = {8, 7, 6, 5, 4, 3, 2, 1};  //in game 0 a scored 1 and b scored 8 
        Tournament.determineWinner(a, b); //it was a tie
        a[0] = 10;
        Tournament.determineWinner(a, b); //a wins
        a[0] = 1;
        b[7] = 10;
        Tournament.determineWinner(a, b); //b wins
      }
    
    }
    
    Answer:
      public static void determineWinner (int [] a, int[] b) {
        int teamaLead =0; //positive is in a's favor, negative in b
        for (int i = 0; i < a.length; i++) { 
          if (a[i] > b[i]) {
            teamaLead++;
          }
          else if (a[i] < b[i]) {
            teamaLead--;
          }
        }
        if (teamaLead > 0) {
          System.out.println("Team A wins!");
        } 
        else if (teamaLead < 0) {
          System.out.println("Team B wins!");
        }
        else {
          System.out.println("It was a tie!");
        }
        
      }
    
  2. (10%) What is wrong with the following program?
    public interface Talkative {
      public void talk();
      
      public String toString() {
        return "";
      }
    }
    
    public class Bobby implements Talkative {
    
      public void talk() {
        System.out.println("Hello friend!");
      }
      
      public String toString() {
        return "My name is Bobby";
      }
    
    }
    
    Answer: An interface cannot implement a method; it can only declare it.
  3. (30%) What does the following program print out?
    public class A {
      private String name;
      
      public int age;
      
      protected double salary;
      
      public static int count = 0;
      
      public A() {
        age = 11;
        count++;
      }
      
      public A(String name, double salary) {
        this.name = name;
        this.salary = salary;
      }
      
      public String toString() {
        return name + " " + age + " " + salary;
      }
    
    }
    
    public class B extends A {
      
      public int score;
    
      public B(String name, double salary, int score) {
        super(name,salary);
        this.score = score;
      }
      
      public String toString(int version) {
        return version + ":" + super.toString() + " score=" + score; 
      }
      
      public static void main(String[] args) {
        A a = new A();
        System.out.println(a);
        A a2 = new A("a2", 10000);
        System.out.println(a2);
        B b = new B("b",20000,33);
        b.score = 22;
        System.out.println(b);
        B b2 = b;
        b2.score = 55;
        System.out.println(b2.toString(1));
        System.out.println(b.toString(2));
        System.out.println("count= " + b.count); 
      }
    }
    
    Answer:
    null 11 0.0
    a2 0 10000.0
    b 0 20000.0
    1:b 0 20000.0 score=55
    2:b 0 20000.0 score=55
    count= 1
    
  4. (40%) Implement a method called check which takes as a parameter a two-dimensional array of integers, you can assume the array is a square of size n, and returns true if the array contains every single integer in the set 1...n^2, false otherwise. Remember that a square array of size n has exactly n^2 elements. (Yes, this is like one of the Sudoku rules).
      /**
       * Returns true if the board contains all the integers from 1...board.length^2
       * Assumes board is a square array.
       * @param board
       * @return
       */
      public static boolean check (int[][] board) {
        boolean[] isIn = new boolean[board.length * board.length]; //all false by default
        for (int rowi = 0; rowi < board.length; rowi++) {
          for (int coli = 0; coli < board.length; coli++) {
            isIn[board[rowi][coli]-1] = true;
          }
        }
        //now return true if they are all true
        for (boolean val : isIn) {
          if (!val) return false;
        }
        return true;
      }
    

Tuesday, September 28, 2010

Test 1 Solution

  1. (10%) The following program fails to compile. Why does it fail to compile?
    public class Broken {
    
      public static void main(String[] args) {
        for (int i = 0; i < 10; i++){
          int result = 0;
          result = result + 1;
        }
        System.out.println(result);
      }
    
    }
    
    Answer: The variable result is used outside its scope, by the println statement.
  2. (10%) The following program also fails to compile. Why does it fail to compile?
    import java.util.Scanner;
    
    public class BrokenA {
      static final double RATE = 0.5;
    
      public double nextYear(double x) {
        return x * RATE;
      }
    
      private static void main(String[] args) {
        int x = 0;
        String name = "Steve";
        Scanner keyboard = new Scanner(System.in);
        String value = keyboard.next();
        BrokenA  ba = new BrokenA();  
        double r = ba.nextYear(value);
        System.out.println(r);
      }
    }
    
    
    Answer:The method nextYear takes a double as an arugment but we are giving it a String.
  3. (30%) What does the following program print out:
    public class RPS {
    
      public static void main(String[] args) {
        String p1 = "PPPSSSRRRPPP"; //notice, only 3 letters used
        String p2 = "RSPPSRPSRPSP";
        for (int i=0; i < p1.length(); i++){
          char c1 = p1.charAt(i);
          char c2 = p2.charAt(i);
          System.out.print (c1 + " " + c2 + " ");
          if (c1 == c2) {
            System.out.println("=");
          }
          else switch (c1) {
          case 'R':
            System.out.println((c2 == 'S') ? 1 : 2);
            break;
          case 'P':
            System.out.println((c2 == 'S') ? 2 : 1);
            break;
          case 'S':
            System.out.println((c2 == 'P') ? 1 : 2);
            break;
          };
        }
      }
    }
    
    Answer:
    P R 1
    P S 2
    P P =
    S P 1
    S S =
    S R 2
    R P 2
    R S 1
    R R =
    P P =
    P S 2
    P P =
    

    Its the game of rock-paper-scissors (RPS).

  4. (50%) Write a program that:
    1. Asks the user for an integer. Assume he does enter an integer. If he enters 0 then the program stops.
    2. Otherwise, if it is a negative integer then the program converts to its positive counterpart (for example, -5 turns into 5).
    3. Otherwise, determine if there are two positive integers X and Y such that the number the user typed is equal to 3*X + 7*Y. If there are, print them, if not then print NONE FOUND. You will do this by brute-force: examine all realistic combinations of possible values of X and Y. (HINT: both of these will always be positive and smaller than...)
    Below is a sample interaction with the program. The users' inputs are in boldface:
    Enter number:3
    3= 3*1 + 7*0
    Enter number:-3
    3= 3*1 + 7*0
    Enter number:5
    NOT FOUND
    Enter number:7
    7= 3*0 + 7*1
    Enter number:11
    NOT FOUND
    Enter number:12
    12= 3*4 + 7*0
    Enter number:21
    21= 3*0 + 7*3
    Enter number:22
    22= 3*5 + 7*1
    Enter number:123456
    123456= 3*6 + 7*17634
    
    Answer:
    import java.util.Scanner;
    
    public class Legal {
    
      public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        while (true) {
          System.out.print("Enter number:");
          int number = keyboard.nextInt();
          if (number == 0) break;
          if (number < 0) number = number * -1;
          int x =0;
          int y =0;
          boolean found = false; //a flag
          for (x = 0; x < number; x++){ 
            for (y=0; y < number; y++){ //number is a bit high here, what should we use?
              if (number == 3*x + 7*y) {
                found = true;
                break;}
            }
            if (found) break;
          }
          if (found) {
            System.out.println(number + "= 3*" + x + " + 7*" + y);
          }
          else {
            System.out.println("NOT FOUND");
          };
        }
      }
    }
    

Tuesday, December 1, 2009

Test 3

145 Test 3: Fall 2009

  1. (20%) What does the following program print out?
    public class MyExceptions {
    
      public int trySomething(int x) throws Exception{
    
        if (x < 0) {
          throw new Exception("X is less than 0");
        }
        return 5;
    
      }
    
    
      public static void main(String[] args){
        MyExceptions m = new MyExceptions();
        try {
          System.out.println("Starting");
          int result = m.trySomething(10);
          System.out.println("Got " + result);
          result = m.trySomething(- 10);
          System.out.println("Got " + result);
          System.out.println("No more tries");
        }
        catch (Exception e){
          System.out.println(e.getMessage());
        }
        System.out.println("Done");
      }
    
    }
    
    Answer:
    Starting
    Got 5
    X is less than 0
    Done
    

  2. (10%) In the program above, what would happen with we removed the whole catch block? Would the program compile or not? If you think it would not compile then explain what the compiler complains about. If you think is would compile then show what the program would print out when run.
    Answer: It does not compile. You cannot have a try without a catch.

  3. (10%) Implement a class called Employee, with data members String name and int salary. Make sure that instances of your Employee can be written out to a binary file. But, do not write the code to write instances to a file, just make sure that instances of Employee can be written out to a binary file.
    Answer:
    public class Employee implements Serializable {
    
      private String name;
      private int salary;
    
      /** Add other methods, as needed. */
    
    }
    

  4. (20%) Given the following text file, called data.txt:
    123432
    3.14151
    Ringo
    
    write a program that reads those three values from the text file into an integer, double, and string variables, respectively.
    Answer:
    import java.util.Scanner;
    import java.io.File;
    import java.io.FileNotFoundException;
    
    public class ReadFile {
    
      public static void main (String[] args){
    
        String fileName = "data.txt";
    
        try {
          Scanner inputStream = new Scanner(new File(fileName));
          int i = inputStream.nextInt();
          inputStream.nextLine();
          double d = inputStream.nextDouble();
          inputStream.nextLine();
          String s = inputStream.next();
          System.out.println("i=" + i + "\nd=" + d + "\ns=" + s);
        }
        catch (FileNotFoundException e){
          System.out.println("File Not Found");
        }
      }
    
    }
    

  5. (20%) A fast way of finding the greatest common divisor (gcd) of two numbers x and y is by using the following recursive definition of gcd(x,y):
    the gcd(x,y) is equal to the gcd of y and x%y,
    the gcd(x,0) is equal to x.
    
    Implement a recursive function that calculates the greatest common division of any two integers.
    Answer:
    public class GCD {
    
      /** Calculate the greatest common division, using the recursive function:
          gcd(x,y) = gcd(y,x%y)
          gcd(x,0) = x  */
      public static int gcd (int x, int y){
            if (y == 0)
              return x;
            return GCD.gcd(y, x%y);
      }
    
      public static void main (String[] args){
        System.out.println(GCD.gcd(10,5));
        System.out.println(GCD.gcd(10,1));
        System.out.println(GCD.gcd(8,6));
        System.out.println(GCD.gcd(121,11));
      }
    
    
    }
    

  6. (20%) The following program contains two compile-time errors. What are they?
    import java.util.ArrayList;
    
    public class Test<Type, E>{
    
      private ArrayList<Type> list;
    
      private ArrayList<E> another;
    
      public Test(){
        list = new ArrayList<E>();
        another = new ArrayList<E>();
      }
    
      public Type badFunction(E x, Type t){
        E y = x;
        Type tt = t;
        list.add(t);
        another.add("Alice");
        Test<String,String> justMe = new Test<String,String>();
        justMe.add("Bob", "Charlie");
        return tt;
      }
    
    }
    
    Answer:
    1. The line
      list = new ArrayList<E>();
      is wrong because the type E should be Type as per the declaration of list.
    2. The line
      another.add("Alice");
      because we cannot assume that the type of another will be ArrayList<String>.