Practice Problems

  1. (Review) toggle show/hide
    Write a Java program GuessNum with these specs:
    1. Generates a random integer between 1 and 5 and tells the user:
      I chose a number between 1 and 5.
      
    2. Prompts the user to guess it:
      Try to guess it: 
      
    3. Suppose 2 was the random number chosen. Your program should generate one of 3 output messages:
      • Number entered not in the 1-5 range.
      • Wrong guess.
      • You got it!
    4. If the user did not get the one chosen, print
      The choice was 2.
      
    Avoid hard-coding the "5" so that it can easily be replaced by a different endpoint, like "6".
  2. (Review) toggle show/hide
    Create program GuessNumMultiple which uses much of the code from the previous problem. The changes are these:
    1. The user is allowed to guess up to 3 times. The program stops if successful. After each guess entered, the program repeats the results of the guess as in (b) of problem #1.
    2. The results are written using as a helper method like this:
      createResults( ... );
      
    3. At the end of 3 trials, if the user has not guessed the number chosen, give a report as in (c) of problem #1.
    Again, avoid hard-coding the "3".
  3. (Objects) toggle show/hide
    We want to play the "game" where a number is chosen between 1 and 20. The user guesses the number and gets a report as to whether the generated number is "higher" (than), "lower" (than), or "equal" (to) the guessed number. The guessing keeps going until the report is "equal", when the program terminates.

    There are two classes involved:
    HiLo.java
    RunHiLo.java     (the main class)
    
    The class HiLo maintains the hidden number. Create these two public methods:
    • a constructor
    • a getter for the generated number
    Other features to add:
    1. allow the user to terminate the program by entering some sentinel number.
    2. Make it so that the user can specify an initial range for the generated number instead of the fixed "20."
  4. (Arrays) toggle show/hide
    Here is an initialized array of student quiz score percentages:
    int[] scores = { 83, 75, 90, 78, 86, };
    
    Write a program, ComputeScores, to print the array contents and then compute and display the average, highest, and lowest scores (average presented as a double with 1 decimal place).
  5. (Arrays) toggle show/hide
    Same as previous, but use the enhanced for loop. Call the program ComputeScores2.
  6. (Objects,Arrays) toggle show/hide
    Create two classes:
    Box.java
    MakeBoxes.java  (main)
    
    The Box class is exactly this:

    Box

    - double width
    - double height
    

    + Box(double, double)
    

    + double getWidth()
    + double getHeight()
    + void setHeight(double)
    + void setWidth(double)
    

    The Box method specs are these:
    • The constructor sets the (width, height) from the parameters.
    • The get methods are standard getters.
    • The set methods are standard setters.
    The main program should:
    1. create an uninitialized array of 3 Boxes
    2. loop through the array, creating a Box with random double width and height between 0 and 10
    3. loop through the array, printing the area of each box
    4. loop through the array, doubling the width of each box
    5. again loop through the array, printing the area of each box
    Alternatives:
    • Make the printing and doubling be done with an enhanced for loop.
    • Make the printing loop be done by a static method in the Main class.
  7. (Objects,Arrays) toggle show/hide
    Create two classes:
    Scores.java
    MakeScores.java  (main)
    
    The Scores class is exactly this:

    Scores

    - int[] scores
    - int numScores
    

    + Scores(int max)
    

    + int getNumScores()
    + void addScore(int score)
    + double getAverageScore()
    

    It uses a partially-filled array scores to keep track of multiple scores where numScores is the number of scores entered. The operations are:
    Scores(int max):      initialize the array of size max
    getNumScores():       getter for numScores
    addScore(int score):  add score into the array
    getAverageScore():    compute and retrieve the average
    
    The driver main program creates an object of this class which can hold up to 10 scores. The program uses the object to enter 3 scores: 67, 77, 82. It retrieves information from the object and reports:
    average of 3 scores is 75.3
    
  8. (2D Arrays) toggle show/hide
    Use this as the basis:
    public class PracProb8 {
      public static void main(String[] args) {
        Random rand = new Random();
        int[][] matrix = ...;
        ...
        printMatrix(matrix);
        ...
      }
     
      private static void printMatrix(int[][] matrix) {
        ...
      }
    }
    Here are the code segments to write:
    1. create matrix as an uninitialized 2D array with 4 rows and 2 columns
    2. initialize matrix with as random ints in the range 1-100,
    3. write printMatrix to print it in a "aesthetic way" using regular for loops
    4. write printMatrix using enhanced for loops for both
    5. compute the sum of the elements in column 0; this has one loop, write it as a regular loop
    6. same as previous part, but write use an enhanced for loop
    In parts b, c, e, avoid using "4" and "2" directly
  9. (2D Arrays) toggle show/hide
    Create a program RaggedTemps which uses a 2-dimensional array with this fixed data:
    33.4,  44.5,  20.1
    -17.2, 18.5 
    55.3,  45.3, -75.3, 88.5 
    
    Write a program which
    1. prints the number of elements in each row
    2. prints the data as a matrix
    3. prints the average value for each row
    The output is like this:
    # entries in row 0 = 3
    # entries in row 1 = 2
    # entries in row 2 = 4
    -------------------------
       33.4   44.5   20.1
      -17.2   18.5
       55.3   45.3  -75.3   88.5
    -------------------------
    average of row 0 = 32.7
    average of row 1 = 0.7
    average of row 2 = 28.5
    --------------------
    
    Write the code using both regular and enhanced for loops. For parts (a) and (c), the outer loop must iterate over the row indexes, but the inner loop can use an enhanced for loop.
  10. (ArrayLists) toggle show/hide
    Write a main class, ArrayListInts with various sections which test working with an ArrayList of Integer, initialized as random numbers:
    ArrayList<Integer> list = new ArrayList<>();
     
    Random rand = new Random();
     
    for (int i = 0; i < 7; i++) {
      list.add(rand.nextInt(100) + 1);
    }
    Here are the code segments to write, in sequence in the main function:
    1. print the list, one per line using a regular for loop
    2. print the list, one per line using an enhanced for loop
    3. compute the average of the numbers in the list
    4. compute the largest number in the list
    5. add 20 to every number in the list
    6. remove the first number in the list which is less than 60
    7. insert the number 200 after the first number in the list which is bigger than 100
    In all cases, avoid using "7" directly or indirectly via a constant. In parts e, f, g, print the list (simply) to verify the outcome.
  11. (ArrayList of Objects) toggle show/hide
    This is a redo of problem #6 using an ArrayList of Boxes instead of an array of Boxes. First, rewrite or create the Box class where the constructor uses the suggested parameters:

    Box

    - double width
    - double height
    

    + Box(double width, double height)
    

    + double getWidth()
    + double getHeight()
    + void setHeight(double)
    + void setWidth(double)
    

    Now write the main class, MakeBoxList, as indicated. The initial change is that you want:
    ArrayList<Box> boxes = new ArrayList<>();
    The main program should:
    1. create a list of 3 Boxes where each is set by a random double width and height between 0 and 10
    2. print the areas of the boxes using a regular for loop. Write a support member function, printAreas, to do this.
    3. Make the support member function, printAreas, print the areas using an enhanced for loop.
    4. double the width and height of each box using a regular for loop
    5. print the areas of the boxes using printAreas
    6. half the width and height of each box each box using an enhanced for loop
    7. print the areas of the boxes using printAreas
    In all parts except (a), avoid using "3" directly or indirectly via a constant.
  12. (Objects,Aggregation) toggle show/hide
    Start with these classes:
    Person: Show Hide
    public class Person {
      private String lastName;
      private String firstName;
      private int age;
     
      public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
      }
     
      public String getLastName() {
        return lastName;
      }  
      public int getAge() {
        return age;
      }
     
      public void setLastName(String lastName) {
        this.lastName = lastName;
      }
      public void setAge(int age) {
        this.age = age;
      }
    }
    select
    Couple: Show Hide
    public class Couple {
      private Person personA;
      private Person personB;
     
      public Couple(Person personA, Person personB) {
        this.personA = personA;
        this.personB = personB;
      }
     
      public Person getPersonA() {
        return personA;
      }
      public Person getPersonB() {
        return personB;
      }
    }
    select
    OverTime (main): Show Hide
    public class OverTime {
     
      public static void main(String[] args) {
        Person john = new Person("John", "Welsh", 26);
        Person judy = new Person("Judith", "Martin", 24);
     
        System.out.println(john);
        System.out.println(judy);
     
        Couple orig_couple = new Couple(john, judy);
     
        System.out.println(orig_couple);
     
        // they get married
        judy.setLastName( john.getLastName() );
     
        System.out.println(orig_couple);
     
        // 5 years later
        Person a = orig_couple.getPersonA();
        Person b = orig_couple.getPersonB();
     
        a.setAge( a.getAge() + 5 );
        b.setAge( b.getAge() + 5 );
     
        System.out.println(orig_couple); 
      }
    }
    select
    First, write toString methods in the People and Couple classes so that the run of the main class looks like this:
    John Welsh(26)
    Judith Martin(24)
    John Welsh(26) + Judith Martin(24)
    John Welsh(26) + Judith Welsh(24)
    John Welsh(31) + Judith Welsh(29)
    
    Then introduce a copy constructor and make fixes in the People and Couple classes so that the orig_couple never changes, i.e., the printout should be:
    John Welsh(26)
    Judith Martin(24)
    John Welsh(26) + Judith Martin(24)
    John Welsh(26) + Judith Martin(24)
    John Welsh(26) + Judith Martin(24)
    
  13. (Recursion) toggle show/hide
    Write a recursive function (static method of the main class) to compute
    The sum of the numbers: 0 + 1 + 2 + ... + n.
  14. (Recursion) toggle show/hide
    Write a recursive function to reverse an array within a specified range. Complete the myReverse function in this code segment:
    import java.util.Arrays;
    import java.util.Random;
     
    public class ReverseArray{
      public static void main(String[] args) {
        Random rand = new Random();
     
        int[] list = new int[10]; // try 9 also
     
        for (int i = 0; i < list.length; ++i) {
          list[i] = rand.nextInt(100) + 1;
        }
     
        System.out.println(Arrays.toString(list));
     
        myReverse(list, 0, list.length);
     
        System.out.println(Arrays.toString(list));
      }
     
      private static void myReverse(int[] list, int from, int to) {
        /*
           if range size is 0 or 1, nothing to do
           else, 
              swap the two values on each end
              call recursively on the portion in between
        */
      }
    }
    select


© Robert M. Kline