Lab 8: Arrays

In this lab, the goal is to practice working with arrays. Work in pairs if you wish.

Problem 1

Write a main in Lab8.java and do the following:

  1. Create an int array named nums containing [1, 2, 2, 3, 2, 5, 3, 6]. Also, introduce an int variable named item with its value 3.
  2. Create a method named occurs that takes two arguments (item and nums) and returns true if item occurs in nums and false if not. And call occurs at least two times in main and print the result. Be sure to choose argument values so that there is at least one call that returns true and another returning false. occurs must look for an element from first index of the array to the last. All the way to the last element if necessary. As soon as it finds item, it should return instead of continuing to the last element of the array.
  3. Create a method named occursCount that takes two arguments (item and nums) and returns the number of times that item occurs in nums. And call occursCount in main and print the result. occursCount must look for the item from first index of the array to the last.
  4. Create a method named occursAtLeast2 that takes two arguments (item and nums) and returns true if item occurs in nums at least twice and false if not. And call occursAtLeast2 in main and print the result. occursAtLeast2 must search from the first index of the array to the last. All the way to the last element if necessary. As soon as it can determine that item occurs at least two times in nums, it should return instead of continuing to the last element of the array.
  5. Create a method named occursExactly2 that takes two arguments (item and nums) and returns true if item occurs in nums exactly twice and false if not. And call occursExactly2 in main and print the result. occursExactly2 must look for the item from first index of the array to the last.
  6. Create a method named twoInRow that takes two arguments (item and nums) and returns true if item occurs in nums two times in a row in the array. and false if not. For example, [0, 1, 1] has two 1's in a row, but [1, 0, 1] does not. And call twoInRow in main and print the result. twoInRow must look for the item from first index of the array to the last and can return early if it sees the item twice in a row.

Please make sure you finish these all! even if you don't finish them all in the lab session. If you have finished these all, you may leave the meeting. If you have not finished them all and yet if you stayed until the end of the session, be sure to finish them outside the lab. You know that we have instructors and TAs who can help you during their office hours. Be sure to get some help.