Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

FIRST SEMESTER 2020 FINAL ONLINE EXAMINATION

BACHELOR DEGREE – Year 2

INTRODUCTION TO PROGRAMMING IN JAVA

CPT105 Semester 1 2020 Final Exam

Part 1 Multiple Choice

25 questions 2 points each.

String type = "reptile";

int legs = 6;

boolean dangerous = true;

String pattern = "striped";

        if (type.equals("mammal")) {

            if (legs == 4) {

                if (dangerous == true) {

                    if (pattern.equals("solid")) {

                        lion();

                    } else {

                        tiger();

                    }

                } else {

                    cat();

                }

            } else {

                System.out.println("Not classified");

            }

        } else if (type.equals("reptile")) {

            if (legs == 4) {

                if (dangerous == true) {

                    crocodile();

                } else {

                    lizard();

                }

            } else if (legs == 0) {

                snake();

            } else {

                System.out.println("Not Classified");

            }

        } else if (type.equals("insect")) {

            if (legs == 8) {

                spider();

            } else if (legs == 6) {

                beetle();

            } else {

                System.out.println("Not Classified");

            }

        } else {

            System.out.println("Not Classified");

        }

1.    When the code above is run, what method is called?

a) The tiger() method is called.

b) The “cat()” method is called.

c) No method is called, but “Not Classified” is displayed.

d) The beetle() method is called.                          

2. Based on the code above, what is the correct description for the if statement given below?

        if (type.equals("reptile")) {

            if (legs == 4) {

                if (dangerous == true) {

                    crocodile();

        } } }

a) If the type is equal to the value of “reptile”, and if the number of legs is equal to four, and if the boolean variable dangerous is set to false, then call the crocodile method.

b) If the type is equal to the value of “reptile”, and if the number of legs is equal to six, and if the boolean variable dangerous is set to false, and if the pattern variable is set to “solid”, then do not call the crocodile method.

c) If the type is equal to the value of “reptile”, and if the number of legs is equal to four, and if the boolean variable dangerous is not set, then call the crocodile method.

d) If the type is equal to the value of “reptile”, and if the number of legs is equal to four, and if the boolean variable dangerous is set to true, then call the crocodile method.

3. Another way to write the if statements above is to use multiple condition if statements.  If we keep the condition values the same, what code will correctly call the cat() method?

a) if (type.equals("mammal") && legs == 4 && dangerous == false) {

b) if (type.equals("mammal") && legs == 4 && dangerous) {

c) if (type.equals("mammal") && legs == 4) {

d) if (type == "mammal" && legs == 4 && dangerous==true) {

 

4. How many times will this for loop run?

a) 1 time

b) Will not run

c) 5 times

d) 4 times

5. This while loop will run 0 times.  Why?

a) The double variable is not declared.

b) The condition is never true.

c) The condition should be <= 5

d) The use of curly brackets is not correct.

6. Given a double variable, double input = 3.1;, how would you cast the double variable to an integer?

a) (double) input;

b) (int) input;

c) Integer.toString(input);

d) Double.parseDouble(input)

7. Using the calculations on the right, after they have been completed, what will the final value of x be?

a) 4

b) 7

c) 4.5

d) 1

8. Using the calculations on the right, after they have been completed, what will the final value of y be?

a) 0

b) 4

c) 0.25

d) 3

9. Using the calculations on the right, after they have been completed, what will the final value of z be?

a) 5

b) 4

c) 14

d) 13

10.  What Java principle is being demonstrated by the following line of code?

public class Hotel extends Travel {

a) Encapsulation

b) Method Overloading

c) Inheritance

d) Constructors

11. What type of variable is the following code?

private double cost;

a) Static variable

b) Local variable

c) Public variable

d) Instance variable

12. What is the name of the superclass in the code example above?

a) Hotel

b) Travel

c) Constructor

d) Class

13. What does the following line of code do?

super();   

a) A new Hotel object is created

b) The constructor of the Hotel object is called

c) The constructor of the Travel object is called

d) The variables are reset

14. What Java principle is being demonstrated by the following line of code?

public boolean equals(Hotel h) {}
public String toString() {}

a) Instance variables

b) Method Overloading

c) Method Overriding

d) Parameter Passing

15. What Java principle does the following code demonstrate:

private double cost;
       public int getCost(){}

a) Encapsulation

b) Shared variables

c) Inheritance

d) Method overloading

16. Which of these statements is correct:

a) A Java file is interpreted on the Java Virtual Machine.

b) A Java file is compiled into bytecode, and then the Java Virtual Machine compiles and runs the bytecode file.

c) A Java file is compiled into bytecode, and then the Java Virtual Machine interprets the bytecode file.

d) A Java file is compiled into assembly language, and then the Java Virtual Machine interprets the assembly file.

17.  Which is a valid declaration and initialization of a float?

a) float f = 2.1f;

b) float f = “2.1f”;

c) float f = new 2.1f;

d) float f = 2.1;

18. Given a circle of radius 3, what is the correct Java code to calculate the area of a circle?

a) double area = Math.pow((Math.PI *3), 2);

b) double area = Math.PI *Math.pow(2, 3);

c) double area = Math.PI *Math.pow(3, 2);

d) double area = 2 * Math.PI *3;

19. Given the String input below, how would we produce the output “Exam”?

        String input = "CPT105 Exam Today";

a) input.substring(7, 11);

b) input.substring(0,6);

c) input.substring(6, 11);

d) input.substring(7);

20. Given the String input below, how would we produce the output “TODAY”?

        String input = "CPT105 Exam Today";

a) input = input.toUpperCase (input.length()-5, input.length()).equalsIgnoreCase();

b) input = input.substring(input.length()-5, input.length()).toUpperCase();

c) input = input.toUpperCase (input.length()-5, input.length());

d) input = input.substring(7, 11).toUpperCase();

21. What Java Class would you use to calculate the difference between dates? 

a) The Date Class

b) The Period Class

c) The Duration Class

d) The getDate() Class

22. Which line of code would correctly instantiate a new LocalDateTime object? 

a) LocalDateTime dateTime = LocalDateTime.of(“2020, 11, 5, 9, 30”)

b) LocalDateTime dateTime = LocalDateTime.of(2020, 11, 5, 9, 30);

c) LocalDateTime dateTime = LocalDateTime.of(2020, 11,5);

d) LocalTime getTime = LocalDate.getTime(22, 40, 10);

23. We wish to create a method named calculate that will receive an integer and a double as arguments and return an integer.  Which method header is correct?

a) public static int calculate(int a, int b);

b) public static void calculate(int a, double b){

c) public static double calculate(double a,b){

d) public static int calculate(int a, double b) {

24. We wish to create a method named checkAndDisplay that will receive 2 boolean arguments, but not return anything.  Which method header is correct?

a) public static void checkAndDisplay (boolean a, boolean b){

b) public static void checkAndDisplay (boolean a, boolean b) ;

c) public static boolean checkAndDisplay (boolean a) {

d) public static boolean checkAndDisplay(String a, String b){

25. Looking at the code on the right, what is represented by B?

a) Access modifier for the method

b) Argument or parameter to the method

c) Return type for the method

d) Return value for the method

Part 2 Code Completion: 50 marks, 4 Questions.

Question 1 (10 marks)

Look at the code below, read it and then complete the code description below by filling in the spaces.

 

This is a method named viewVal that allows the user to choose a value in an array using keyboard input.  It has no parameters and returns a String.  It is not part of an object and is a static method.  The method first creates an array of Strings of length 3, and assigns values.  We then declare and initialise a Scanner object, and display a message to the user to instruct them to choose a suitable index.  The input will be wrapped in a try catch, and the String will be parsed to an integer.  If the String does not parse, a NumberFormat Exception is thrown, which will then be caught and an error message will be displayed to the user.

If the input is correctly parsed to an integer, then the method attempts to select the appropriate value from the array.  It will attempt to assign and display the string using the index entered by the user.  If the user inputs a number larger than the size of the array, an ArrayIndexOutOfBounds Exception will be thrown and caught, with an error message displayed to the user.  

Finally, if a valid input has been received, the appropriate String will be returned from the method.

Question 2 (20 marks)

a) Create a class to store data about a book.  A book has a title, an author, and a number of pages.  You should use sensible variable types and names, and create instance variables, a constructor, appropriate encapsulation, and override the inherited methods   (10)

 

2 marks – private instance variables, 2 strings and an int, sensible names

2 Marks – constructor, 3 variables passed in, no type of method, variables assigned

2 Marks – encapsulation, getters and private variables

2 Marks – Sensible toString, returns a String

2 Marks – Equals method – not expecting much, 2 marks if a good attempt made,1.5 if didn’t attempt to parse object first, 1 mark if didn’t compare all 3 fields

 

 

 

b) Declare and initialise an array of length 5 with 5 books.   You do not need to create the method headers. (2 marks)

 

Book[] books = new Book[5];

        

        books[0] = new Book("Asimov", "Foundation", 250);

        books[1] = new Book("Asimov", "Foundation and Empire", 100);

        books[2] = new Book("Asimov", "Second Foundation", 200);

        books[3] = new Book("Asimov", "Foundations Edge", 50);

        books[4] = new Book("Asimov", "Foundation and Earth", 210);

1 mark for array, 1 mark for sensible answers,

c) Create a method to identify the book with the highest number of pages, displaying the highest number of pages.  You do not need to create the method headers. (4 marks)

int highest = books[0].getPages();

        for(int i = 0; i<books.length; i++){

            if(books[i].getPages()> highest )

                highest = books[i].getPages();

        }

        System.out.println("Highest: " + highest);

highest variable declared – 1 mark

For loop – 1 mark (0.5 if array. Length not used)(0.5 if highest not calculated)

calculate highest value – 1 mark

display highest pages – 1 mark

d) Create a method to identify the average number of pages for all the books in the array.  You do not need to create the method headers. (4 marks)

double mean = 0;

        double total = 0;

        for(int i = 0; i<books.length; i++){

                total = total + books[i].getPages();

        }

        mean  = total/books.length;

        System.out.println("Mean page number: " + mean);

mean and total variables declared – 1 mark

For loop – 1 mark (0.5 if array. Length not used)(0.5 if total not calculated)

calculate mean value – 1 mark

Question 3: (10 marks)

Complete the following Java private helper method to count the number of empty strings in an array of strings using recursion.

Do not use any loops.  Submissions with loops will not pass.

Sample test cases:
String[] arr1 = {"123", "", "abc"};
System.out.println(countEmptyString(arr1));     → 1
String[] arr2 = {"", "", "", ""};
System.out.println(countEmptyString(arr2));     → 4

public static int countEmptyString(String[] arr) {

        return countEmptyString(arr, 0);

}



Marking scheme

10 marks for passing all test cases
0 marks penalty for first incorrect submission
1 mark penalty for each subsequent incorrect submissions

 

 

 

 

Question 4: (10 marks)

 

a) You have been asked to simulate a simple car park.  A car park has a number of spaces, and each space can be either full or not full, and can hold one vehicle, either a car, or a bike, stored as a vehicle.  A space can add or remove a vehicle.  It can also return whether it is full, and return all information about the space as a string.

The main CarPark class stores parking spaces as an arraylist, and has methods to add a vehicle, remove a vehicle, and check for fraud (returns a boolean).

All Vehicles have a registration and an owner, stored as Strings, and can return their data.  To check for fraud, Vehicles also have an equals method.  Each Car has a model, stored as a String, and is a Vehicle.  Each Bike has a length, stored as a double, and is also a Vehicle.  The system does not require you to compare any objects, but it does require information about the vehicle/bike/car to be output as a string.  

Draw a simple UML diagram showing the basics for this project.  You should specify the classes, the relationships between them, and all attributes and methods.  You should not write any code, only draw the diagram. (10 marks)

 

   

5 classes created – 2 marks (1 mark if no Vehicle, 1 mark if no boxes around them)

Correct variables – 2 marks (1 for some mistakes, be quite flexible)

ToString methods – 2 marks

Constructors and getters – 1 marks (0.5 if partially there)

FraudMethod in carpark – 1 mark

Relationships – 2 marks (quite relaxed, as long as there are lines connecting)