CS140 40 10 F Sol
CS140 40 10 F Sol
Student ID:
Section No.:
Instructions:
1. Answer 4 questions; there are 4 questions in 7 pages.
2. Write your name on each page of the exam paper.
3. Write your answers directly on the question sheets. Use the ends of the question pages for
rough work or if you need extra space for your answer.
4. If information appears to be missing from a question, make a reasonable assumption, state
your assumption, and proceed.
5. No questions will be answered by the invigilator(s) during the exam period.
Page 1 of 8
Consider the following sequence number generated by 9 repeated calls of sr.nextInt(3) where
sr is a variable of type SecureRandom:
1 0 1 0 0 2 0 2 2
import java.security.SecureRandom;
public class Maze
{
public static void main(String[] args)
{
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.print(maze());
}
System.out.println();
}
System.out.println('^');
} // method main
_ _
| |
^
Page 2 of 8
The following Java program asks the user to enter a number between 1 and 10. If he/she enters a wrong
number, the program will ask him/her again and again for another number. The program ends when the
user enters a correct value.
There are 5 errors in this program. Find and fix the errors by filling the erroneous instruction line number
and its correction in the table below.
1 import java.util.Scanner
2
3 public static ReadValue {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6 int n;
7 do
8 System.out.print("Enter a number between 1 and 10 = ");
9 n = nextInt();
10 } while(n < 1 && n > 10 );
11 }
12 }
Answer: (for each correct line 0.5, and for each correction 1.5)
1 import java.util.Scanner;
7 do {
9 n = input.nextInt();
Page 3 of 8
Write a Java method called abbreviate that receives a non-empty alphabetic string and returns its
abbreviation; a string composed of capitalized first letter of each word from the original string.
Call examples:
System.out.println(abbreviate("meters"));
System.out.println(abbreviate("Saudi Arabia"));
System.out.println(abbreviate("Stock keeping unit"));
Will output:
M
SA
SKU
Answer:
Page 4 of 8
The program purpose of this question is to help students in elementary school to test their knowledge
about multiplication tables. Complete the following program by defining 2 methods fillAnswers and
correctAnswers where their descriptions are respectively provided in the next 2 pages.
import java.util.Scanner;
Page 5 of 8
Running example (student answers are entered after the “?” mark):
Answer (6 marks):
Page 6 of 8
Running example:
Answer (6 marks):
Page 7 of 8