Advanced Loops, Arrays and Static Methods

Introduction to the use Loops with Arrays, and Static Methods

Lab Exercise 5

State controlled and sentinel controlled loops[i]

Often in a computer program a loop is needed to continue execution until a specific event or action occurs. When this event or action occurs, a value is set to a variable which causes the loop to terminate. These loops will then halt execution due to the value now assigned to the variable causing the loop condition to become false.

One example of using a state controlled loop is with the use of a Main Program loop. This type of loop will continue execution of the entire program until the user decides to exit. Once the user decides to exit the program, a value will be set to signify that the user clicked the exit button, chose the exit choice in a menu, etc. This variable can hold a boolean value to signify an attempt to exit the program. When boolean values are used to determine the termination of a loop, the identifier that holds this value is often called a flag. The names of the identifiers used to control these loops should relate to the job that they are accomplishing. For example examine the program in Appendix A on Page 3.

From this example you can see that a separate method is used to prompt the user with choices and get input according to the choices the user makes. In this method the user is asked whether he/she would like to continue. If the user enters a c a true value is passed back to main and the main program loop continues to execute. If the user enters an e, a false value is passed back to main and the main program loop halts. When the main program loop halts the program stops execution by reaching the end of the main method.

A problem the MenuChoice() method does not address very well is if the user enters a value other than the ones shown in the user prompt. Using another state-controlled loop inside the new MenuChoice() method, the user will have the opportunity to re-enter a new choice that is valid. This will provide a more user friendly environment that expects that the user will make a mistake and handle the mistake gracefully. Please look at Appendix B on page 6for the new MenuChoice() method.

Notice with this statecontrolled method there is a value that never changes. The done identifier is set to false and is never set to true within the loop body. This is because with the natural flow of the program the method will terminate with a return value when a correct choice is made. Setting the done identifier to true in the switch statement would be useless since the method would return a value before the done identifier can be evaluated by the loop condition. Remember that when a method returns a value, all further execution of that method stops and the value in the return statement is then returned to the calling method. In this case the calling method is main and the values returned to main are either true or false.

The major difference between a state controlled loop and a sentinel controlled loop is that the state controlled loop evaluates a boolean value that is often set when the state of the program changes. A sentinel controlled loop will continue execution until a special value is stored in the sentinel identifier. The sentinel identifier’s values are evaluated by the loop and the loop will halt execution when the sentinel value[ii] is reached.

For example, you write a program that prompts the user for prices of items and keeps a running total of the prices entered. The loop will continue running as long as the user enters a Positive number. When the loop encounters a negative number, the loop will halt and the total will be display to the user. The negative number entered by the user is considered the sentinel value witch causes the loop to halt.

In any case whether you use a State controlled loop or a sentinel controlled loop, these loops will continue execution until a specific state, or value occurs within the program. This will provide a more dynamic program that will execute according to varying different types of eventsor states that may occur within the program.

Arrays in Java

There are times when you create a program you wish to group data of the same type together. For example you may want to group together test scores, or Automobiles, Student names, etc. When grouping data types together in “a single composite data structure” this is called creating an array of that data type.

Like objects, arrays require the use of references. This means that they are passed to methods as references and not by value. The data that is manipulated within the method is the same data that is referenced in the calling method. In other words when you make changes to the array reference passed to the method, these changes become permanent.

Unlike objects, arrays are a group or list of data of the same type. Every element of the array is of the same type and can not be different. For example you can have an array of students but not an array of students and teachers.

Once the size of an array has been declared this size cannot be changed. You can declare the array reference without giving the size. Later in the program, possibly after getting user input, the size of the array may be given to the reference. Please see the example in figure 1 on page 5.

Figure 1

This illustrates how to declare an

array of integer of size 20

Each element of the array can be accessed through its index. The index of an element is an integer greater than or equal to 0 that represents the position in the array that element is located. For example with the above array, the first element can be accessed with MyNumbers[0]. Every array contains elements that start at the index of 0 and end at the index of size-1. With the previous example the index of the first element is of course 0 and the index of the last element would be 19. At first glance since the size of the array is 20, most people would think that the last index of the array is 20. This is not the case however because the size of the array is the number of elements in the array and since the size of the array is 20 and the index starts at 0 the last index must be 19 (you can do the math if you wish).

Because all of the data in an array is sequentially listed and the index of each element is an integer, a for loop[1]can be used to access every element in the array. This is particularly useful when you have to print out each element of the array to the user or store new values to every element in the array. Please examine the code in figure 2 on page 6.

Figure 2

The above code illustrates how a for loop

can be used to access each element of the array.

From the above example you can see that Array references can be used to access each element of the array and the length of the array can be accessed from the length attribute. The reason that i is initialized here to MyNumbers.length-1 is to set the i variable to the last index of the array. This is so that each element from the last index down to 0 will be filled with data. Remember the last element of the array is size – 1 not size sincethe length attribute will always hold the number of elements in the arrayand not the index of the last element.

In addition to filling the array for loops can be used to print each element out. This can be observed with the next example in figure 3 on page7.

Figure 3

The above example shows how all the

elements of the array can be printed out from

index 0 to index 19

Static methods and attributes in Java

A static method can be used to create a library of methods that are implemented without object instantiation. These methods within a class are used by using the class name followed by the methods name. You have been using static methods with the use of the showInputDialog() method of the JOptionPane class.

At no time did you have to instantiate the JOptionPane class in order to use any of its methods. This is primarily due to the fact that the showInputDialog() method contains the static keyword in the method heading. This is also seen with the Math class and all of the methods that you have been using within this class. The String class however requires instantiation before any of the methods can be used. Therefore the charAt() method of the string class is an instance method and not a static method.

Static methods must follow a couple of rules though. They can be used in ANY class including those that have instance methods but they can only access other static methods. They also can only access attributes of the class that are also static. In other words static methods can only access other static methods and attributes within the same class. Please see the example in appendix C on page12.

From the example listed, you can see that the static key word is used to label the static attributes and static methods of the ghost class. The static attribute is the PowerDot identifier and the value that is stored in this identifier is accessible by all instances of ghost. The EatPowerDot() and the TimedOut() method are both static methods that are used to set the value of the PowerDot attribute of the ghost class.

When called from another method ghost.EatPowerDot() will set the value of the PowerDot attribute to true. The ghost.TimedOut() method will set the value of the PowerDot attribute to false. In both cases, an instance of the class is not needed to call these methods. This is due to the fact that these methods are static methods and not instance methods.

Also note that in these methods the only attribute that they can access is the static attribute PowerDot. These are the only attributes and methods that they have access to because these static methods do not have access to the instance methods and attributes of the class[2]. Please examine how this class can be used in main in appendix D on page 15.

Lab Exercise

Create a class that will have an integer array as an attribute. The size of the array will be inputted from the user. This class will have the ability to fill the array with unique random numbers from 1 to array size. The class will also have the ability to sort the array using a bubble sort.

Along with this the class will have all of the basic methods explained in previous exercises.

Exercise Review

Key Words

for / element / length / instantiation
static / attribute / pass by reference / Objects
array / sentinel / pass by value / JOptionPane
index / State controlled / post-increment / pre-increment

Review Questions

  1. Can you have an array of objects?
  2. If you can how?
  3. What type of loop is usually used to traverse or go to every element in an array?
  4. Every element in the array has an _____ to mark its position in the array?
  5. Can an array index be negative?
  6. Why or why not?
  7. Can static methods access instance methods? why or why not?
  8. Can instance methods access static methods? why or why not?
  9. Can Static methods access instance attributes? why or why not?
  10. Do static methods require object instantiation?

Practice Exercises

  1. Create a program that will fill an array of characters randomly and sort those characters from A to Z.
  2. Create an array of integers and ask the user to fill that array. Then sum up all of the values of that array.
  3. Create an array of integer given a low number and then a high number. The array size will be the range of the two numbers. Fill that array with number from low to high. sum up that array.
  4. Write a class that will have static methods called bubblesort, printArray, and FillArray that will use integer array references as parameters. Call these methods from main.

  1. Appendix A

This program is an example how a state controlled

Loop can be used as the main program loop.

import javax.swing.*;

//Author: Prof. Thomas G. Re

//CMP 210

//Description: This program illustrates to the student the use of sentinels and state //controlled loops.

public class MyProg

{

//main method of the program

public static void main(String[] args)

{

boolean ProgramExit = false;

//The Main Program Loop. As long as the variable ProgramExit remains

//false this loop will continue to execute.

while(!ProgramExit)

{

//MenuCoice() is a method that will return either a true or false //value and assign this value to the identifier ProgramExit

ProgramExit = MenuChoice();

}

System.out.println("The program exited normally");

}

//This Method will provide a menu and ask the user for a choice using //JoptionPane.showInputDialog(). If the user wants to exit this method will return //a true value. Otherwise this method returns a false value.

public static boolean MenuChoice()

{

String Question, UserInput;

char choice;

//Place the prompt in the string Question using string concatenation

Question = “Please Make a choice\n”;

Question = Question + “ C)ontinue\n”;

Question = Question + “ E)xit\n”;

UserInput = JOptionPane.showInputDialog(Question);

//Remove case by making all input one case

UserInput = UserInput.toUpperCase();

//Get the character from the string at the 0th position in the string

choice = UserInput.charAt(0);

//determine the return value of the method according to the choice that the //user makes.

switch(choice)

{

case ‘C’: System.out.println("User wants to continue");

returnfalse; //when return statement is used here a //break is not needed

case ‘E’: System.out.println("User wants to quit");

returntrue; //when return statement is used here a //break is not needed

default:

//the user did not enter a valid choice from the menu

System.out.println(“This was not a valid choice”);

}

//for now there is no means to handle the wrong choices entered by the //user. This is illustrated in the method shown in Appendix B

return false;

}

}

Appendix B

public static boolean MenuChoice()

{

String Question, UserInput;

char choice;

boolean done = false;

Question = “Please Make a choice\n”;

Question = Question + “ C)ontinue\n”;

Question = Question + “ E)xit\n”;

while(!done)

{

UserInput = JOptionPane.showInputDialog(Question);

UserInput = UserInput.toUpperCase();

choice = UserInput.charAt(0);

switch(choice)

{

case ‘C’: System.out.println("User wants to continue");

returnfalse; //when return statement is used here a //break is not needed

case ‘E’:System.out.println("User wants to quit");

returntrue; //when return statement is used here a //break is not needed

default:

//the user did not enter a valid choice from the menu

System.out.println(“This was not a valid choice”);

}

//return statements in methods halt any further execution of the //method. The only time this loop stops is when the return //statement executes.

}

}

Appendix C

This is an example of the use

of the key word static with in a class

/*****************************************************************

*Ghost Class

*

*By: Prof. Thomas G. Re

*

*Description: This class is used for demonstrating to the students the

*use of a class and the constructors of a class including:

*

*1) default constructor

*2) overloaded constructor

*3) copy constructor

*

*This class also demonstrates Accessesor functions, and static variables

*and methods

*

*Copyright (C) 2003:

*

*This is to be used for educational use only

******************************************************************/

import javax.swing.*;

publicclass ghost

{

private String Colour;

private String TheName;

privateint Speed;

privateint x;

privateint y;

privatestaticboolean PowerDot; //static attribute

/**************************************************************

*

*Default Constructor

*

*Description: initializes all of the private data members of the

*ghost class to zero

*

*Input:No inputs

*

*Ouput:No outputs or returned values

**************************************************************/

public ghost()

{

Colour = "";

TheName = "";

Speed = 0;

x = 0;

y = 0;

PowerDot = false;

}

/***************************************************************

*

* Overloaded Constructor

*

*Description: The overloaded constructor have parameters that are

*used to set the values of the private data members to the values

*passed to the method.

*

*Input: The color of the ghost, the speed of the ghost, the name

*of the ghost, the position of the ghost and if the Power Dot is

*eaten.

*

*Output: no output or returned values in this method

*

***************************************************************/

public ghost(String Colour, String TheName, int Speed, int x, int y,

boolean PowerDot)

{

this.Colour = Colour;

this.TheName = TheName;

this.Speed = Speed;

this.x = x;

this.y = y;

this.PowerDot = PowerDot;

}

//This is a static method that will let all of the gohsts know

//that the powerDot has been eaten

publicstaticvoid EatPowerDot()

{

PowerDot = true;

}

//This is a static method that will reset the ghosts back when the