Show solutions

145 Final Test

  1. (5%) Write a complete Java program that, when you run it, prints out:
    Hello world!
    public class HelloWorld{
      public static void main(String[] args){
        System.out.println("Hello world!");
      }
    }
    
  2. (5%) Implement a function that takes as input a string which contains a sentence in English and returns the number of vowels in the sentence. You can assume that all the letters in the sentence you are given are in lower case. And, in case you forgot, the vowels are a,e,i,o,u.
    public class Sentence{
    
      /** @param sentence is assumed to be all in lower case.
          Returns the number of vowels in sentence. */
      public static int countVowels(String sentence){
        int count =0;
        for (int i=0; i < sentence.length(); i++){
          char c = sentence.charAt(i);
          if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
            count++;
        }
        return count;
      }
      
      public static void main(String[] args){
        System.out.println(Sentence.countVowels("To be or not to be,"));
        System.out.println(Sentence.countVowels("That is the question."));
        System.out.println(Sentence.countVowels("aeiou and sometimes y"));
    
      }
    }
    
  3. (5%) Write a function which takes as input an integer x and returns an array that contains all the even numbers less than or equal to x but bigger than or equal to 0, from biggest to smallest. For example, for x = 5 it should return the array (let's call it a):
    a[0] = 4
    a[1] = 2
    a[2] = 0
    Note that x could be odd or even.
    public class Even{
    
      /** @param x must be non-negative
          Returns array of even numbers in x .. 0. */
      public static int[] getEven(int x){
        int[] result = new int[x/2 + 1];
        int i;
        if (x%2 == 0)
          i = x;
        else
          i = x-1;
        int j =0;
    
        for (;i >= 0; i -= 2)
          result[j++] = i;
        return result;
      }
    
      //Unit testing.
      public static void main(String[] args){
        int[] a = getEven(10);
        for (int i=0; i < a.length; i++)
          System.out.println(a[i]);
        a = getEven(11);
        for (int i=0; i < a.length; i++)
          System.out.println(a[i]);
      }
    }
    
  4. (10%) You are given the following code:
    public class Person{
      /** The name of the person.*/
      private String name;
    
      /** 'M' for male and 'F' for female. */
      private char sex;
    
      /** Height in inches. */
      private double height;
    
      public Person(String name, char sex, double height){
        this.name = name;
        this.sex = sex;
        this.height = height;
      }
    
      public String toString(){
        return name;
      }
    
      public char getSex(){
        return sex;
      }
    
      public void setSex(char sex){
        this.sex = sex;
      }
    
      public double getHeight(){
        return height;
      }
    
      public void setHeight(double height){
        this.height = height;
      }
    }
    
    Implement a Student class that extends the Person class. Each student has a major, which is represented by a string. The Student class also needs to implement a constructor, and a getSexMajor() function which returns a String with the student's sex, a dash '-', and the major. For example, the following program:
    public class Student extends Person{ /** Student's major. */ private String major; public Student(String name, char sex, double height, String major){ super(name,sex,height); this.major = major; } public String getSexMajor(){ return getSex() + "-" + major; }
    public static void main(String[] args){ Student a = new Student("John", 'M', 60.5, "CSCE"); Student b = new Student("Jill", 'F', 65.5, "CSCE"); System.out.println(a + " " + a.getSexMajor()); System.out.println(b + " " + b.getSexMajor()); }
    }
    should print out
    John M-CSCE
    Jill F-CSCE
  5. (10%) Write a function called getBonus() for the Employee class below which returns the amount of bonus pay the employee will receive. You, as the boss, have determined that the final bonuses will be determined following these rules:
    public class Employee {
      /** In dollars */
      private double salary;
    
      /** In years. */
      private int age;
    
      /** Level is from 0 (lowest) to 6 (highest) */
      private int level;
    
      /** Appraisal grade for this year:
          It is one of: 'A', 'B', 'C', 'D' or 'F' */
      private char grade;
    
      public Employee(double salary, int age, int level, char grade){
        this.salary = salary;
        this.age = age;
        this.level = level;
        this.grade = grade;
      }
    
    
    public double getBonus(){ if (grade == 'D' || grade == 'F') return 0; double bonus = 0; if (level >= 3) bonus = salary * 0.05; else bonus = salary * 0.06; if (grade == 'A') bonus += 1000; if (bonus > 5000) bonus = 5000; return bonus; } public static void main(String[] args){ Employee[] people = new Employee[8]; people[0] = new Employee(120000, 65, 6, 'B'); people[1] = new Employee(110000, 61, 5, 'A'); people[2] = new Employee(84000, 42, 5, 'A'); people[3] = new Employee(50000, 35, 3, 'F'); people[4] = new Employee(44000, 32, 2, 'C'); people[5] = new Employee(40000, 28, 1, 'B'); people[6] = new Employee(1200, 25, 0, 'A'); people[7] = new Employee(1200, 23, 0, 'C'); for (int i=0; i< people.length; i++) System.out.println(people[i].getBonus()); }
    }
  6. (15%) What does the following program print out?
    //A.java
    public class A {
      protected int[] x;
      
      public A(){
        x = new int[3];
        x[0] = 0;
        x[1] = 1;
        x[2] = 2;
      };
    
      public String getX(){
        String result = "";
        for (int i =0; i < x.length; i++)
          result += x[i] + "-";
        return result;
      }
    
      public void setXi(int index, int value){
        x[index] = value;
      }
    
      public void setX(int[] x){
        this.x = x;
      }
      
      public String toString(){
        return "A";}
    }
    
    //B.java
    public class B extends A{
    
      public B(){
        super ();};
    
      public void setXi(int index, int value){
        x[index] = value + 10;
      }
      
      public String toString(){
        return "B";}
    }
    
    //C.java
    public class C extends B{
      public C(){super ();};
    
      public void setXi(int index, int value){
        super.setXi(index, value - 5);
      }
    
      public String toString(){
        return "C";}
      
      public static void main (String[] args){
        A[] v = new A[3];
        v[0] = new A();
        v[1] = new B();
        v[2] = new C();
        for (int i =0; i < v.length; i++){
          System.out.println(v[i]);
          if (v[i] instanceof B) {
            System.out.println("It is a B");
          }
        }
        System.out.println("---");
        A a = new A();
        System.out.println(a.getX());
        int[] x = new int[3];
        x[0] = 5;
        x[1] = 6;
        x[2] = 7;
    
        a.setX(x);
        System.out.println(a.getX());
        a.setXi(0,0);
        System.out.println(a.getX());
        a.setXi(1,1);
        System.out.println(a.getX());
        x[2] = 2;
        System.out.println(a.getX());
    
        System.out.println("---");
        B b = new B();
        System.out.println(b.getX());
        b.setXi(1,1);
        System.out.println(b.getX());
        A a2 = (A)b;
        a2.setXi(2,2);
        System.out.println(a2.getX());
        System.out.println(b.getX());
    
        System.out.println("---");
        C c = new C();
        System.out.println(c.getX());
        c.setXi(0,5);
        System.out.println(c.getX());
    
      }
    }
    
    A
    B
    It is a B
    C
    It is a B
    ---
    0-1-2-
    5-6-7-
    0-6-7-
    0-1-7-
    0-1-2-
    ---
    0-1-2-
    0-11-2-
    0-11-12-
    0-11-12-
    ---
    0-1-2-
    10-1-2-
    
  7. (20%) A liberal arts professor, unable to write his own programs, has hired you to develop a program to keep track of his students' grades and calculate their final grade. He currently keeps his grades in a file that looks like:
    Billy Joe Armstrong 100 85 75 100 
    Mike Dirnt 44 23 5 44
    Tre Cool 5 0 0 0
    Jean Valjean 24 60 1 0
    Tito Puente 80 80 40 88
    That is, each line in the file starts with the name of the student followed by the grades that student has received. Before reading the file you will know how many tests/homeworks there are (4 in this example) and how many students are in the file (5 in this case). Your job is to:
    1. Read a file into the proper data structure. Note, you will be graded on design.
    2. Implement a general method for calculating the final average given the prof-supplied weights. That is, given an array of doubles (which you can assume add up to 1), implement a function to calculate the students' final average. For example, if the weights are
      w[0] = .1
      w[1] = .1
      w[2] = .2
      w[3] = .6
      
      then the final grade is calculated by adding 10% from the students' first grade, 10% from the second, 20% from the third, and 60% from the fourth.
    import java.io.*;
    import java.util.*;
    
    public class Undergrad {
    
      /** The grades */
      private int[] grades;
    
      /** The weight for each grade.  Note that this is static since it is
       the same for all students.  Another way to do it is to store the
       weights in the Classroom class and pass them as an argument to the
       getWeightedAverage() function each time it is called.
      */
      private static double[] weights;
    
      private String name;
    
      public Undergrad (Scanner in, int numGrades){
        name = "";
        while (!in.hasNextInt()){
          name += in.next() + " ";
        }
        grades = new int[numGrades];
        for (int i=0; i < numGrades; i++)
          grades[i] = in.nextInt();
        in.nextLine();
      }
    
      public static void setWeights(double[] weights){
        Undergrad.weights = weights;
      }
    
      public double getWeightedAverage(){
        double result =0;
        for (int i =0; i < grades.length; i++)
          result += grades[i] * Undergrad.weights[i];
        return result;
      }
    
      public String toString(){
        String result = name;
        for (int i=0; i < grades.length; i++){
          result += grades[i] + " ";
        }
        return result;
      }
    }
      
    
    import java.io.*;
    import java.util.*;
    
    public class Classroom {
      Undergrad[] students;
    
      public Classroom (String filename, int numStudents, int numGrades){
        try{
          Scanner in = new Scanner (new File(filename));
          students = new Undergrad[numStudents];
          for (int i=0; i < numStudents; i++){
            students[i] = new Undergrad(in, numGrades);
          }
        }
        catch (FileNotFoundException e){
          System.out.println(e);
        }
      }
    
      public String toString(){
        String result = "";
        for (Undergrad u : students){
          result += u + "\n";
        }
        return result;
      }
    
      public String getFinals(){
        String result = "";
        for (Undergrad u : students){
          result += u + " " + u.getWeightedAverage() + "\n";
        }
        return result;
      }
    
      public static void main (String[] args){
        Classroom kotter = new Classroom("grades.txt", 5, 4);
        System.out.println(kotter);
        double [] w = {.1, .1,.2,.6};
        Undergrad.setWeights(w);
        System.out.println(kotter.getFinals());
      }
    }
    
  8. (30%) A 3x3 normal magic square is a 3x3 grid where the numbers on each row, each column, and both diagonals all add up to the same number, and the square contains the numbers 1 to 9 exactly. For example, the following is the Lo Shu magic square:
    4 9 2
    3 5 7
    8 1 6
    Implement a function which, given a two-dimensional 3 by 3 array of ints returns a boolean that tells us if the given square (represented by the array) is a normal 3 by 3 magic square or not.
    public class Magic {
    
      public static boolean check(int[][] a){
        int sum,s;
        sum=0;
        for (int col = 0; col< 3; col++) //first set the sum (15 always?)
          sum += a[0][col];
    
        //check the next two rows
        s = 0;
        for (int row = 1; row < 3; row++){
          s = 0;
          for (int col = 0; col< 3; col++) 
            s += a[row][col];
          if (s != sum)
            return false;
        }
    
        //check columns
        for (int col = 0; col< 3; col++) {
          s = 0;
          for (int row = 0; row < 3; row++){
            s += a[row][col];
          }
          if (s != sum)
            return false;
        }
    
        //check diagonal 1
        s =0;
        for (int row = 0; row < 3; row++){
          s += a[row][row];
        }
        if (s != sum)
          return false;
    
        //check diagonal 2
        s =0;
        for (int row = 0; row < 3; row++){
          s += a[row][2 - row];
        }
        if (s != sum)
          return false;
    
        //check that the numbers 1..9 appear
        //We use an array of booleans and mark each one as we find it.
        boolean[] appears = new boolean[9];
        for (int i=0; i < 9; i++){
          appears[i] = false;
        }
    
        //Check each one
        for (int col = 0; col< 3; col++) {
          for (int row = 0; row < 3; row++){
            int num = a[row][col];
            if (appears[num-1]) //its easy to forget that -1.
              return false; //oops, this number appears twice!
            appears[num-1] = true;
          }
        }
    
        //I could check here that all the values in appears are true but
        // since there are 9 positions in both appears and a[][], I know
        // that if we get to this point then all the values in appears[]
        // must be true!
        return true;
      }
    
      public static void main (String[] args){
        int[][] loshu = {{4,9,2},{3,5,7},{8,1,6}};
        System.out.println(Magic.check(loshu));
        int[][] no1 = {{4,9,2},{3,7,5},{8,1,6}};
        System.out.println(Magic.check(no1));
        int[][] no2 = {{4,9,2},{3,3,5},{8,1,6}};
        System.out.println(Magic.check(no2));
      }
      /** From wikipedia: The Lo Shu square (3×3 magic square)
    
    Chinese literature dating from as early as 2800 BC tells the legend of
    Lo Shu or "scroll of the river Lo". In ancient China, there was a huge
    flood. The people tried to offer some sacrifice to the river god of
    one of the flooding rivers, the Lo river, to calm his anger. Then,
    there emerged from the water a turtle with a curious figure/pattern on
    its shell; there were circular dots of numbers that were arranged in a
    three by three nine-grid pattern such that the sum of the numbers in
    each row, column and diagonal was the same: 15. This number is also
    equal to the number of days in each of the 24 cycles of the Chinese
    solar year. This pattern, in a certain way, was used by the people in
    controlling the river. */
    
    }