CS 312 - Midterm 2 Review Sheet

Here are some review questions. There will definitely be questions on the exam that are not similar to the ones below. Re-work examples and exercises from class and discussion to test your understanding of different topics. Remember that you will not have your textbook, class notes, or the compiler to help you write programs on the exam, and there will be much more time pressure than there is for programming assignments.

1. Write a method that takes an integer n, and returns a String. Assume the integer n is an odd integer between 1 and 9. If the returned String is printed, it should display a box like the one below, when n = 9. The integers in the last row will be n.

-----1-----
----333----
---55555---
--7777777--
-999999999-



2. Write a method compareEntries that takes two arrays of integers, and returns the lowest index in which the arrays contain the same value. If there is no position in the which the two arrays contain the same values, return -1.
compareEntries({4, 6, -1, 8, 20}, {88, 20, -1, 4, 9, 0}) --> 2
compareEntries({11, 0, 2}, {5, 8, 2, 1}) -->2
compareEntries({6, 7, 8, 9}, {2, 3}) --> -1

public static int compareEntries(int[] a, int[] b)
{
    int shortestLen = Math.min(a.length, b.length); //length of shortest array

    for(int i = 0; i < shortestLen; i++)
    {
       if(a[i] == b[i])  return i;
    }
    return -1;
}

3. What is the value of these expressions? The type should be clear from the way you write the values, i.e., Strings in double quotes, doubles with decimal points.


4. Write a method getRange that takes two integers m and n, and returns an array of integers that contains the integers between m and n in increasing order.
getRange(2, -1) --> [-1, 0, 1, 2]
getRange(0, 3) --> [0, 1, 2, 3]

This was an in-class example.

5. Write a method that takes a File object. Each line in the file contains quiz grades for a single student, like this:
Samantha  9  4  10  8
Elvis  4  2   9
Orrin  9  2  1  8  7  6  5

For each student in the file, your method will print the student's name and the sum of the student's quiz scores, e.g.,

Samantha: quiz total = 31
Elvis: quiz total = 15
Orrin: quiz total = 38

public static void printTotals(File grades) throws IOException
{
    Scanner reader = new Scanner(grades);
    while(reader.hasNextLine())
    {
       // get the line and create a Scanner for it
       String line = reader.nextLine();
       Scanner lineScanner = new Scanner(line);

       // display name, compute quiz total
       System.out.print(lineScanner.next() +": ");
       int sum = 0;

       while(lineScanner.hasNextInt())
       {
             sum += lineScanner.nextInt();
       }
      
       System.out.println("quiz total = " + sum);
    }
}




6. Write a method negativePositive that takes an array of integers, and returns an array that contains 3 integers. The first value in the returned array is the number of negative integers in the array, the second value is the number of zeroes in the array, and the third value is the number of positive integers in the array.
negativePositive({4, 90, -3, -1, 0, 0, 88, -5, -2}) -> [4, 2, 3]

public static int[] negativePositive(int[] arr)
{
    int pos = 0;
    int zero = 0;
    int neg = 0;

    for(int i = 0; i < arr.length; i++)
    {
        if(arr[i] > 0) pos++;
        else if (arr[i] == 0) zero++;
        else neg++;
    }

    int[] results = new int[3];
    arr[0] = neg;
    arr[1] = zero;
    arr[2] = pos;

    return arr;
}

7. Write a program that prompts the user for a file name, and continues to prompt the user until the specified file exists and is readable. Assume the file contains Strings, characters, doubles, etc., all types of tokens. Create a new file called doubles.txt, and write all floating-point numbers in the file to this new file.



8. Write a program that prompts the user for 2 integers, m and n. Then print the squares of these integers, in increasing order, separated by commas:
Please enter two integers: 5  3
The squares are: 9, 16, 25

Please enter two integers: 1  3
The squares are: 1, 4, 9

public static void printSquares(int m, int n)
{
    int min = Math.min(m, n);
    int max = Math.max(m, n);

    int len = min+max + 1;

    if(len == 1)
       System.out.println(min*min);
    else
    {
       for(int i = min; i < max; i++)
          System.out.print(i*i + " ,");
       System.out.println(max*max);
    }
}

9. Consider the following method:

public static void mystery(int x)
{
    int y = 0;
    while (x % 2 == 0)
    {
       y++;
       x /= 2;
    }
   System.out.println(x + " " + y);
}

What is the output for the following calls:

mystery(19);  Output: 19  0
mystery(42);  Output: 21  1
mystery(40);  Output: 5   3

10. Write a sentinel loop that repeatedly prompts the user for numbers, and once the number -1 is entered, displays the maximum and minimum number entered. Here is a sample run:

Type a number (-1 to stop): 8
Type a number (-1 to stop): 2
Type a number (-1 to stop): 19
Type a number (-1 to stop): 3
Type a number (-1 to stop): -1
Maximum was 19.
Minimum was 2.

We've done this program in class.

11. Write a program that compares two files and prints information about the differences between them. For example, if data1.txt contains:

This file has a great deal f
text in it which needs to

be processed.

And data2.txt contains:

This file has a grate deal of
text in it which needs to

bee processed.

Your output would be:

Differences found:
Line 1:
< This file has a great deal of
> This file has a grate deal of

Line 4:
< be processed.
> bee processed.

public class FileDiff
{
    public static void main(String[] args) throws IOException
    {
       Scanner scan1 = new Scanner(new File("data1.txt"));
       Scanner scan2 = new Scanner(new File("data2.txt"));
       int lineCount = 0;

       while(scan1.hasNextLine() && scan2.hasNextLine())
       {
          lineCount++;
          String line1 = scan1.nextLine();
          String line2 = scan2.nextLine();

          if(!(line1.equals(line2)))
          {
             System.out.println("Line " + lineCount + ": ");
             System.out.println("< " + line1);
             System.out.println(" > " + line2);
          }
      }
}


12. Prompt the user to enter 10 Strings, and store those strings in an array. Pass this array of Strings to a method getLengths. getLengths will return an array that contains the lengths of the strings in the array.

public class StringStuff
{
    public static void main(String[] args)
    {
       String[] text = new String[10];
       System.out.print("Enter 10 strings: ");
       Scanner scan = new Scanner(System.in);
       for(int i = 0; i < 10; i++)
          text[i] = scan.nextLine();

       int[] lengths = getLengths(text);

    }

    public static int[] getLengths(String[] arr)
    {
       int[] strLengths = new int[arr.length];

       for(int i = 0; i < arr.length; i++)
          strLengths[i] = arr[i].length();  // arr[i] is a String

       return strLengths;
    }
}


         

13. Write a for loop that multiplies each entry in an array numbers of doubles by 2. Could you do this with a for each loop? Why or why not?

int[] arr = ...; // assume arr has been initialized

for(int i = 0; i < arr.length; i++) arr[i] *= 2;

A for each loop cannot be used, since we want to modify the array entries.

14. Write a few lines of code that illustrate how Arrays.equals() and Arrays.toString() can be used.

See class notes.