CISC 1115
Introduction to Programming Using Java
Midterm Sample Questions


  1. Given the following code:
    			Scanner scanner = new Scanner(System.in);
    
    			int x, m;
    			System.out.print("first? ");
    			m = scanner.nextInt();
    			System.out.print("second? ");
    			x = scanner.nextInt();
    
    			if (x > m) m = x;
    
    			System.out.println(m);
    		

    1. What is output if the numbers entered are 4 and 7 (in that order)?
    2. What is output if the numbers entered are 10 and 5 (in that order)?
    3. In general, what does the code do?

  2. Write a code fragment that prompts the user at the keyboard for two numbers and prints their sum, product and whether either divides the other evenly. You should declare all variables used. You need not write a full program, i.e., no imports nor class/main method boilerplate should be written.

  3. Find and fix three errors in the following code. For each one state whether it is a compilation or execution/logical error:

    			Scanner scanner = new Scanner(System.out);
    
    			System.out.print("number 1? ");
    			int x = scanner.nextDouble();
    			System.out.print("number 2? ");
    			int y = scanner.nextInt();
    			
    			System.out.println("The sum of " + x + " and " + y + " is " + (x * y));
    		

  4. Given the following code, show the values of the variables x, y, z, m1, and m2, as they change during execution:

    			int x = 2, y = 7, z = 3;
    			int m1 = x;
    			int m2 = x;
    			if (y > m1) m1 = y;
    			if (y < m2) m2 = y;
    			if (z > m1) m1 = z;
    			if (z < m2) m2 = z;
    		

  5. Given the following method

    		int f(int x) {
    			if (x >=  0) 
    				return x;
    			return -x;
    		}
    		

  6. Write a full program that reads the data file exam.text which consists of a header value followed by that number of integers, and prints out the numbers in the file and their squares. The program should contain the method int calcSquare(int n) that accepts a value and returns its square (you must write calcSquare).

    As an example, if the file exam.text contains the following data:

    4
    
    6
    2
    7
    9
    		

    the output should be

    6: 36
    2: 4
    7: 49
    9: 81
    		

    (Remember the first number in the file is the header value, and not one of the numbers to be squared).

    The program should

    Do NOT program to the example; i.e., you should not assume the program only runs on the above data file. It must be able to run on ANY file containing a header value followed by that number of integers