User Tools

Site Tools


cs257:hw0

Model for quickly testing single methods

Below I've sketched a class that could serve as a test program for our linearSearch method, but with comments describing what they might do. Other ways of writing this code are certainly possible; if you have a better way, go for it!

  // Test class 
  public class SearchTest {
 
     // need a constant here giving the array size
     
     public static void main(String[] args) {
       // create an array of the proper size
       // initialize the array with random values in some reasonable range
       // call linearSearch several times, searching for both items in array and not in array,
       //  printing out the results
       // NOTE: it's helpful to print both the target search for and the result of the search
     }
     
     // method to test
     public static boolean linearSearch(int[] data, int target) {
       // try to find target in the array data
     }
  }

One question that has come up: if you're generating random data, how do you know what's in the array and what isn't? There's lots of ways to do this too, but here's a hint: generate only positive values for the array. Now you know what isn't in the array? Negative integers. And you know what is in the array, right? data[0] is in the array - there's nothing that says you can't call linearSearch with values that are already in the array. So is data[1], data[2], etc. If you wanted to, you could test the search routine 100 times for items in the array, once for each item in the array, and around 4 billion times for items not in the array (everything else).

Refresher on running from the command-line

This is based on the example above; you certainly don't have to name your class the same thing I did. In the Terminal Window:

  • gedit SearchTest.java
  • javac SearchTest.java
  • java SearchTest

That assumes there are no compiler errors after running javac, but we both know there probably will be.

If you are familiar with a Java IDE (such as Eclipse, BlueJ, or NetBeans) you may use them for this assignment, but for short assignments with just one class, the command-line method is simple and straightforward. Eventually, though, you should wean yourself off gedit. It's kind of the low-end of editors; other editors include features that make programmers more productive, but at the cost of a higher learning curve.

In any case, all programs you produce for this class must work when run from the command line.

cs257/hw0.txt · Last modified: 2017/02/07 11:37 by scarl