CPSC 124, Spring 2014
Sample Answers to Test #1

Question 1. Some short questions...

a) What is machine language?

b) What is a variable?

c) Define the term algorithm.

Answer.

a) Machine language is a programming language consisting of instructions that are executed directly by the computer's CPU. Machine language instructions are coded as binary numbers. Each type of computer has its own machine language.

b) A variable is a memory location that has a name so that it can be referred to in a program. A variable can store a value. In Java, a given variable can store only one type of value.

c) An algorithm is an unambiguous, step-by-step procedure for performing some task, which is guaranteed to end after a finite number of steps.

Question 2. A novice programmer tries to write a Java code segment that prints out the numbers 0, 1, 2, 3, 4, 5. The programmer writes the following code, which contains a syntax error and two semantic errors:

   int num;
   for (num = 0; num < 5; num++); {
        system.out.println(num);
   }

a) What is the syntax error (which will be found by the compiler)?

b) What are the semantic errors (which cause the code segment to give the wrong output)?

c) Fix all the errors: Rewrite the for loop so that it does in fact print out the numbers 0, 1, 2, 3, 4, 5.

Answer.

a) The syntax error is that "system" should start with an upper case letter. It should be System.out.println. The compiler will report an "unknown symbol" since it doesn't recognize "system."

b) The semicolon after "for (num = 0; num < 5; num++)" is a semantic error, since the semicolon is an empty statement and is the only thing that is inside the loop. The other semantic error is using < instead of <=, which causes the loop to run only for the numbers 0, 1, 2, 3, and 4. The 5 at the end of the desired output is omitted.

c) To get the desired output:

   int num;
   for (num = 0; num <5; num++) {
       System.out.println(num);
   }

Question 3. Write a Java code segment that will print out 1000 random integers, where each integer is in the range 1 through 100 inclusive. (They do not have to be different.)

Answer.

   int i;
   for (i = 0; i < 1000; i++) {
       int number;
       number = (int)(100*Math.random()) + 1;
       System.out.println(number);
   }

Here's another solution, using a while loop:

   int count, number;
   count = 1;
   while (count <= 1000) {
       number = (int)(100*Math.random() + 1);
       System.out.println(number);
       count = count + 1;
   }

Question 4. The price of a buffet depends on a person's age. For people 60 years old or older, the price is $10. For children 12 years or younger, the price is $6. Otherwise, the price is $12. Write a code segment that asks the user's age and then tells the user their price. The program should say either "Your price is $6", "Your price is $10," or "Your price is $12."

Answer.

    int age;
    System.out.print("What is your age? ");
    age = TextIO.getlnInt();
    if (age >= 60) {
        System.out.println("Your price is $10.");
    }
    else if (age <= 12) {
        System.out.println("Your price is $6.");
    }
    else {
        System.out.println("Your price is $12.");
    }

Here's another solution that uses plain if statements:

    int age;
    System.out.print("What is your age? ");
    age = TextIO.getlnInt();
    if (age >= 60) {
        System.out.println("Your price is $10.");
    }
    if (age <= 12) {
        System.out.println("Your price is $6.");
    }
    if (age > 12 && age < 60) {
        System.out.println("Your price is $12.");
    }

Question 5. Show the exact output produced by the following code segment:

   int n, x, y;    
   x = 1;    
   y = 5;    
   while ( x <= y ) {    
       x = x*3;    
       y = y*2;    
       n = y / x;    
       System.out.println(n + " " + x + " " + y);    
   }    

Answer.

    3 3 10
    2 9 20
    1 27 40
    0 81 80

Question 6. Draw the picture that is produced by the following paintComponent subroutine. The drawing area is 800-by-600 pixels.

    protected void paintComponent(Graphics g) {    
        g.setColor(Color.WHITE);    
        g.fillRect(0,0,800,600);    
        g.setColor(Color.BLACK);    
        int n,k;    
        k = 300;    
        for (n = 100; n < 500; n = n + 100) {    
            g.drawLine( 100, n, k, n );    
            k = k + 100;    
        }    
    }    

Answer.

(Note that four lines are drawn, with n = 100, 200, 300, and 400. The for loop stops before n = 500. The value of k is 300 at the beginning, and it goes up by 100 at the end of each execution of the loop. So the effect is the same as:

    g.drawLine(100,100,300,100);
    g.drawLine(100,200,400,200);
    g.drawLine(100,300,500,300);
    g.drawLine(100,400,600,400);

This draws the four horizontal lines shown.)

Question 7. Write a complete Java program (starting with public class...) that does the following: Ask the user for a String, and read it. Ask the user for a char, and read it. Use a loop to count the number of times that the user's character occurs in the user's input line. Output the result. The result should say something similar to, "The character k occured 7 times."

Answer.

public class CountChar {

    public static void main(String[] args) {
        String input;
        char ch;
        int count;
        int i;
        System.out.print("Enter your string: ");
        input = TextIO.getln();
        System.out.print("Enter your char:   ");
        ch = TextIO.getlnChar();
        count = 0;
        for (i = 0; i < input.length(); i++) {
            if (input.charAt(i) == ch) {
                count = count + 1;
            }
        }
        System.out.println("The character " + ch + 
                                   " occurred " + count + " times.");
    }

}

Question 8. What are exceptions in Java, and what do exceptions have to do with try..catch statements?

Answer. An "exception" can be "thrown" when an error or other exceptional condition occurs while a program is being executed. For example, a NumberFormatExcepion will be thrown when Integer.parseInt(str) is executed if the String str does not contain a legal integer. When an exception is thrown, it will crash the program, unless it is "caught" by a try..catch statement. When a specified exception occurs during the execution of the try part of the statement, control jumps immediately to the catch part of the statement, and execution of the program procedes normally from there.

Question 9. Write a short essay about style in programming. Discuss what it means and why it is important. Give at least two examples of specific style rules for Java programs, and explain why each rule is a good idea. (Please write an essay, with full sentences and paragraphs!)

Answer. Good programming style makes it easier for a human to read and to understand a computer program. The computer doesn't care at all about style; all it cares about is correct syntax. What the program looks like or whether it even makes sense makes no difference as far as the computer is concerned. However, programs are also read by people, who have to understand how to use them and how they work. People need to be able to modify programs to bring them up to date or to track down bugs. To make that as easy as possible, it is important that programs be readable by humans.

There are many rules of good programming style. One of the most important is to properly indent a program to show its structure. Without indentation, it can be almost impossible for a reader to see the flow of control in the program. Also very important are comments. Comments are text that is added to a program for the sake of human readers only. They are completely ignored by the computer. Comments can help the reader to understand the purpose of the program and the logic of its design. It is also helpful to use meaningful variable names that will help the user to understand what is going on.