CS 151 Fall 2007 Lab 6

While and for loops, Scanner

The goal for this lab is to gain experience using different kinds of loops for repeating the same command or series of commands multiple times.  We will also see how to solicit input from the user via the terminal window using the Scanner class.  Part of the lab involves creating a class that gets input from the user in the terminal window and performs an action based on that input.  The other part of the lab involves implementing a class to perform those actions with the user's input.

 

  1. Open BlueJ either by selecting it from the Dock or navigating to it in the Applications folder and double clicking it.

  2. Mount your network directory/folder so that you can access the lab after you leave Olin 323.  Go to the Finder and from the Go menu select Connect to Server....  Type afp://fileserver1 or choose it from the list of selections and select the Personal volume when prompted.

  3. From the Project menu select New Project.  Select your computer from the drop down menu.  Then scroll down and open the Volumes folder and then the Personal folder inside it.  Scroll down the long list of folders until your find yours.  Create a project called "Lab6" in your personal network folder.

  4. Create a class called CSMath and remove the default instance variable and method that BlueJ puts in the class.  Add a public static method called numberOfBinaryDigits that takes a single parameter of type int (don't forget to give it a name) and also returns an integer.  It will calculate the number of binary digits required to store the specified number.  In the body of the method, i.e. between {  } add the following lines (with your variable name in place of _____):

 

int numberOfDigits = 1;

       

//keep dividing by 2 and adding 1 to numberOfDigits until result < 1

while (_____ / 2 >= 1)

{

______ = ______ / 2;

     numberOfDigits++;

}

 

Add a final line that returns the contents of the numberOfDigits variable.  Compile and fix any syntax errors, but don't test it yet.

 

  1. Create a class called CSMathApplication.  Remove the default instance variable and method that BlueJ creates in the class.  Add to the very first line of your class a line to import the Scanner class that is part of the java.util package (import java.util.Scanner;).  Also add a main method to the class.  Recall that the main method is always public and static, returns void and takes a single parameter called args that is of the String array type (denoted String[]).  Don't forget to add { and } to denote the beginning and end of the method's body.

 

  1. In the body of the main method, define a variable of type Scanner called input and initialize it by calling the Scanner class constructor with the parameter System.in (new Scanner(System.in)).  Add a line after that which prints the message "Please enter a positive integer: " to the terminal window using the print() rather than println() method.  In the next line, call the nextInt() method for input and assign the result to a variable of type int.  Don't forget to give your variable a meaningful name (int ____ = input.nextInt()). 

    Finally, add a line that calls your static
    numberOfBinaryDigits()method in the CSMath class with your variable as a parameter (CSMath.numberOfBinaryDigits(____)) and prints the integer the user entered and the integer that the method returns to the terminal window in a phrase like "The number of binary digits need for ___ is ____."  Use println() for this message and remember you can use + to concatenate strings.

 

  1. Test by calling the main method of CSMathApplication in BlueJ.  Don't enter any arguments in the pop-up window that appears and click "OK".  In the terminal window that appears enter a number.  Good test cases include 0, 1, 2, and 1023.  What do you expect to get and does your program produce those results?  Which is correct the program or your expectation?

 

  1. [Optional] Your book has some useful information on using the Logger class to help debug your program (see Advanced Topic 5.6 on page 190).  Instead of printing information about your method's execution to the terminal window it prints them to a log.  To enable logging add the command import java.util.logging.*; as the first line in your CSMathApplication class (even before the class interface/declaration).  Then use the method Logger.global.info() instead of System.out.println() (it works the same way, but just send the result to a different place.  The advantage of using Logger is that you can leave commands in your final version and users of your class won't see those messages that are helpful to you the developer.  To turn logging off add the command Logger.global.setLevel(Level.OFF) at the very beginning of your main.  Try adding a call to the info() method for each of the variables that contain a user-entered value right after input.nextInt() assigns them a value to verify they are correctly set to what the user enters.  See Java class libraries for additional logging information if interested.

 

  1. Add to the end of the main method in your CSMathApplication class lines that ask the user to enter the number of Fibonacci numbers to display and assign the user's reply to an integer variable (repeat what we did for numberOfBinaryDigits(). Then add a line that calls the static method displayFibonnaciNumbers() with variable that contains the user's input as a parameter (CSMath.displayFibonnaciNumbers(___);).   The method will return void so you don't need to assign it to anything.  ThatŐs what void means: nothing, emptiness, nada.

 

  1. See Exercise P6.4 on page 241 of your book for an explanation of the Fibonacci numbers.  Add a static method called displayFibonnaciNumbers() that returns void and takes a single integer parameter.  Use a for loop and the specified parameter to compute and display each Fibonacci number on a separate line in the terminal window.  The first and second Fibonacci numbers are both 1.  The third Fibonacci number is the sum of the first and second ones, and the n­th Fibonacci number is the sum of the (n-1)st and (n-2)nd ones.  Hence, you need to store the last two numbers computed to get the next one.  Don't forget to update the value of the last two numbers inside the for loop.  You may need some logic to check for a parameter value less than 1 and possibly to handle the case when only the first Fibonacci should be printed.  Work through it on paper. 

    Test by running the main method in CSMathApplication and entering the desired values in the terminal window. 
    A command of CSMath. displayFibonnaciNumbers (7); should display


1

1

2

3

5

8

13

 

  1. See Exercise P6.6 on page 243 of your book.  Add to your main method in CSMathApplication the lines needed to get an integer to factor from the user and store it in a variable.  After that add a line that calls the static method displayIntegerFactors() in the CSMath class (it will return void).

 

  1. Add a static displayIntegerFactors() method to your CSMath class that returns void and takes a single integer parameter.  You should print each factor of the specified parameter (assumed to be a positive integer) on a separate line.  For example CSMath.displayIntegerFactors(8); should display


2
2
2

 

Start by creating and initializing an integer variable to 2 (called factor for example).  If the number is divisible by factor (2) you should print factor (2), and otherwise you should add 1 to factor and repeat until a factor is found that divides the number.  Recall that the % operator gives the remainder of division.  For example 3%2 is equal to 1, and 4%2 is equal to 0.  Once you find a factor that divides the number and print the factor, call the method again (yes you can call a method from itself!) with the number/factor as the parameter (new number to factor).  This is an example of recursion.  You will need to add a check somewhere to make sure this process doesn't go on forever.  In infinite loop is a very common mistake when working with while loops.  Consider it another rite of passage. If this happens DON'T PANIC.  To have BlueJ halt execution of method go to the project window.  In the lower left corner you should see a whit and red striped animated bar (like a barbershop pole or candy cane).  Control-click (Windows right-click) on that bar and select "Reset Machine" or hold down the shift and open apple keys and type R.  See, no reason to panic.

 

  1. Time permitting, modify your main method in CSMathApplication to first prompt the user for which CSMath method they want to run.  Have them enter a character or number for their choice, e.g. 1 for numberOfBinaryDigits(), 2 for displayFibonnaciNumbers(), 3 for displayIntegerFactors().  Use the appropriate Scanner class method to read this value (nextInt() or next() for Strings), ask for and read a second input which is what you were previously asking for the method they chose.

 

  1. Finally if you still have time.  Modify the above selection of method to run to repeat the process of asking the user what they want to do, getting the needed input, and doing it until the user signals that they want to stop or quit by entering some sentinel value like "Q" or -1 or 0.  See section 6.4 of your book for discussion on sentinel values and their use.

 

  1. I'm impressed!  I really didn't expect you to get all that done in 80 minutes.