archive-edu.com » EDU » H » HWS.EDU

Total: 727

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Javanotes 7.0, Section 4.3 -- Parameters
    different from printing out a boolean and so forth so that each of these operations requires a different subroutine Note by the way that the signature does not include the subroutine s return type It is illegal to have two subroutines in the same class that have the same signature but that have different return types For example it would be a syntax error for a class to contain two subroutines defined as int getln double getln This is why in the TextIO class the subroutines for reading different types are not all named getln In a given class there can only be one routine that has the name getln with no parameters So the input routines in TextIO are distinguished by having different names such as getlnInt and getlnDouble 4 3 4 Subroutine Examples Let s do a few examples of writing small subroutines to perform assigned tasks Of course this is only one side of programming with subroutines The task performed by a subroutine is always a subtask in a larger program The art of designing those programs of deciding how to break them up into subtasks is the other side of programming with subroutines We ll return to the question of program design in Section 4 6 As a first example let s write a subroutine to compute and print out all the divisors of a given positive integer The integer will be a parameter to the subroutine Remember that the syntax of any subroutine is modifiers return type subroutine name parameter list statements Writing a subroutine always means filling out this format In this case the statement of the problem tells us that there is one parameter of type int and it tells us what the statements in the body of the subroutine should do Since we are only working with static subroutines for now we ll need to use static as a modifier We could add an access modifier public or private but in the absence of any instructions I ll leave it out Since we are not told to return a value the return type is void Since no names are specified we ll have to make up names for the formal parameter and for the subroutine itself I ll use N for the parameter and printDivisors for the subroutine name The subroutine will look like static void printDivisors int N statements and all we have left to do is to write the statements that make up the body of the routine This is not difficult Just remember that you have to write the body assuming that N already has a value The algorithm is For each possible divisor D in the range from 1 to N if D evenly divides N then print D Written in Java this becomes Print all the divisors of N We assume that N is a positive integer static void printDivisors int N int D One of the possible divisors of N System out println The divisors of N are for D 1 D N D if N D 0 Dose D evenly divide N System out println D I ve added a comment before the subroutine definition indicating the contract of the subroutine that is what it does and what assumptions it makes The contract includes the assumption that N is a positive integer It is up to the caller of the subroutine to make sure that this assumption is satisfied As a second short example consider the problem Write a private subroutine named printRow It should have a parameter ch of type char and a parameter N of type int The subroutine should print out a line of text containing N copies of the character ch Here we are told the name of the subroutine and the names of the two parameters and we are told that the subroutine is private so we don t have much choice about the first line of the subroutine definition The task in this case is pretty simple so the body of the subroutine is easy to write The complete subroutine is given by Write one line of output containing N copies of the character ch If N 0 an empty line is output private static void printRow char ch int N int i Loop control variable for counting off the copies for i 1 i N i System out print ch System out println Note that in this case the contract makes no assumption about N but it makes it clear what will happen in all cases including the unexpected case that N 0 Finally let s do an example that shows how one subroutine can build on another Let s write a subroutine that takes a String as a parameter For each character in the string it should print a line of output containing 25 copies of that character It should use the printRow subroutine to produce the output Again we get to choose a name for the subroutine and a name for the parameter I ll call the subroutine printRowsFromString and the parameter str The algorithm is pretty clear For each position i in the string str call printRow str charAt i 25 to print one line of the output So we get For each character in str write a line of output containing 25 copies of that character private static void printRowsFromString String str int i Loop control variable for counting off the chars for i 0 i str length i printRow str charAt i 25 We could use printRowsFromString in a main routine such as public static void main String args String inputLine Line of text input by user System out print Enter a line of text inputLine TextIO getln System out println printRowsFromString inputLine Of course the three routines main printRowsFromString and printRow would have to be collected together inside the same class The program is rather useless but it does demonstrate the use of subroutines You ll find the program in the file

    Original URL path: http://math.hws.edu/javanotes/c4/s3.html (2016-02-07)
    Open archived version from archive


  • Javanotes 7.0, Section 4.4 -- Return Values
    of the function Some people prefer to use a single return statement at the very end of the function when possible This allows the reader to find the return statement easily You might choose to write nextN like this for example static int nextN int currentN int answer answer will be the value returned if currentN 2 1 test if current N is odd answer 3 currentN 1 if so this is the answer else answer currentN 2 if not this is the answer return answer Don t forget to return the answer Here is a subroutine that uses this nextN function In this case the improvement from the version of the subroutine in Section 4 3 is not great but if nextN were a long function that performed a complex computation then it would make a lot of sense to hide that complexity inside a function static void print3NSequence int startingValue int N One of the terms in the sequence int count The number of terms found N startingValue Start the sequence with startingValue count 1 System out println The 3N 1 sequence starting from N System out println System out println N print initial term of sequence while N 1 N nextN N Compute next term using the function nextN count Count this term System out println N Print this term System out println System out println There were count terms in the sequence Here are a few more examples of functions The first one computes a letter grade corresponding to a given numerical grade on a typical grading scale Returns the letter grade corresponding to the numerical grade that is passed to this function as a parameter static char letterGrade int numGrade if numGrade 90 return A 90 or above gets an A else if numGrade 80 return B 80 to 89 gets a B else if numGrade 65 return C 65 to 79 gets a C else if numGrade 50 return D 50 to 64 gets a D else return F anything else gets an F end of function letterGrade The type of the return value of letterGrade is char Functions can return values of any type at all Here s a function whose return value is of type boolean It demonstrates some interesting programming points so you should read the comments This function returns true if N is a prime number A prime number is an integer greater than 1 that is not divisible by any positive integer except itself and 1 If N has any divisor D in the range 1 D N then it has a divisor in the range 2 to Math sqrt N namely either D itself or N D So we only test possible divisors from 2 to Math sqrt N static boolean isPrime int N int divisor A number we will test to see whether it evenly divides N if N 1 return false No number 1 is a prime int maxToTry The largest divisor that we need to

    Original URL path: http://math.hws.edu/javanotes/c4/s4.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 5.2 -- Constructors and Object Initialization
    want as long as their signatures are different that is as long as they have different numbers or types of formal parameters In the PairOfDice class we might have a constructor with no parameters which produces a pair of dice showing random numbers public class PairOfDice public int die1 Number showing on the first die public int die2 Number showing on the second die public PairOfDice Constructor Rolls the dice so that they initially show some random values roll Call the roll method to roll the dice public PairOfDice int val1 int val2 Constructor Creates a pair of dice that are initially showing the values val1 and val2 die1 val1 Assign specified values die2 val2 to the instance variables public void roll Roll the dice by setting each of the dice to be a random number between 1 and 6 die1 int Math random 6 1 die2 int Math random 6 1 end class PairOfDice Now we have the option of constructing a PairOfDice object either with new PairOfDice or with new PairOfDice x y where x and y are int valued expressions This class once it is written can be used in any program that needs to work with one or more pairs of dice None of those programs will ever have to use the obscure incantation int Math random 6 1 because it s done inside the PairOfDice class And the programmer having once gotten the dice rolling thing straight will never have to worry about it again Here for example is a main program that uses the PairOfDice class to count how many times two pairs of dice are rolled before the two pairs come up showing the same value This illustrates once again that you can create several instances of the same class public class RollTwoPairs public static void main String args PairOfDice firstDice Refers to the first pair of dice firstDice new PairOfDice PairOfDice secondDice Refers to the second pair of dice secondDice new PairOfDice int countRolls Counts how many times the two pairs of dice have been rolled int total1 Total showing on first pair of dice int total2 Total showing on second pair of dice countRolls 0 do Roll the two pairs of dice until totals are the same firstDice roll Roll the first pair of dice total1 firstDice die1 firstDice die2 Get total System out println First pair comes up total1 secondDice roll Roll the second pair of dice total2 secondDice die1 secondDice die2 Get total System out println Second pair comes up total2 countRolls Count this roll System out println Blank line while total1 total2 System out println It took countRolls rolls until the totals were the same end main end class RollTwoPairs Constructors are subroutines but they are subroutines of a special type They are certainly not instance methods since they don t belong to objects Since they are responsible for creating objects they exist before any objects have been created They are more like static member subroutines but they are not and cannot be declared to be static In fact according to the Java language specification they are technically not members of the class at all In particular constructors are not referred to as methods Unlike other subroutines a constructor can only be called using the new operator in an expression that has the form new class name parameter list where the parameter list is possibly empty I call this an expression because it computes and returns a value namely a reference to the object that is constructed Most often you will store the returned reference in a variable but it is also legal to use a constructor call in other ways for example as a parameter in a subroutine call or as part of a more complex expression Of course if you don t save the reference in a variable you won t have any way of referring to the object that was just created A constructor call is more complicated than an ordinary subroutine or function call It is helpful to understand the exact steps that the computer goes through to execute a constructor call First the computer gets a block of unused memory in the heap large enough to hold an object of the specified type It initializes the instance variables of the object If the declaration of an instance variable specifies an initial value then that value is computed and stored in the instance variable Otherwise the default initial value is used The actual parameters in the constructor if any are evaluated and the values are assigned to the formal parameters of the constructor The statements in the body of the constructor if any are executed A reference to the object is returned as the value of the constructor call The end result of this is that you have a reference to a newly constructed object For another example let s rewrite the Student class that was used in Section 1 I ll add a constructor and I ll also take the opportunity to make the instance variable name private public class Student private String name Student s name public double test1 test2 test3 Grades on three tests Student String theName Constructor for Student objects provides a name for the Student The name can t be null if theName null throw new IllegalArgumentException name can t be null name theName public String getName Getter method for reading the value of the private instance variable name return name public double getAverage Compute average test grade return test1 test2 test3 3 end of class Student An object of type Student contains information about some particular student The constructor in this class has a parameter of type String which specifies the name of that student Objects of type Student can be created with statements such as std new Student John Smith std1 new Student Mary Jones In the original version of this class the value of name had to be assigned by a program after it created the

    Original URL path: http://math.hws.edu/javanotes/c5/s2.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 5.4 -- Programming Example: Card, Hand, Deck
    same value are sorted by suit Note that aces are considered to have the lowest value public void sortByValue Again there are a few things in the implementation of the class that you won t understand at this point but that doesn t stop you from using the class in your projects The source code can be found in the file Hand java 5 4 2 The Card Class We will look at the design and implementation of a Card class in full detail The class will have a constructor that specifies the value and suit of the card that is being created There are four suits which can be represented by the integers 0 1 2 and 3 It would be tough to remember which number represents which suit so I ve defined named constants in the Card class to represent the four possibilities For example Card SPADES is a constant that represents the suit spades These constants are declared to be public final static ints It might be better to use an enumerated type but I will stick here to integer valued constants The possible values of a card are the numbers 1 2 13 with 1 standing for an ace 11 for a jack 12 for a queen and 13 for a king Again I ve defined some named constants to represent the values of aces and face cards When you read the Card class you ll see that I ve also added support for Jokers A Card object can be constructed knowing the value and the suit of the card For example we can call the constructor with statements such as card1 new Card Card ACE Card SPADES Construct ace of spades card2 new Card 10 Card DIAMONDS Construct 10 of diamonds card3 new Card v s This is OK as long as v and s are integer expressions A Card object needs instance variables to represent its value and suit I ve made these private so that they cannot be changed from outside the class and I ve provided getter methods getSuit and getValue so that it will be possible to discover the suit and value from outside the class The instance variables are initialized in the constructor and are never changed after that In fact I ve declared the instance variables suit and value to be final since they are never changed after they are initialized An instance variable can be declared final provided it is either given an initial value in its declaration or is initialized in every constructor in the class Since all its instance variables are final a Card is an immutable object Finally I ve added a few convenience methods to the class to make it easier to print out cards in a human readable form For example I want to be able to print out the suit of a card as the word Diamonds rather than as the meaningless code number 2 which is used in the class to represent diamonds Since this is something that I ll probably have to do in many programs it makes sense to include support for it in the class So I ve provided instance methods getSuitAsString and getValueAsString to return string representations of the suit and value of a card Finally I ve defined the instance method toString to return a string with both the value and suit such as Queen of Hearts Recall that this method will be used automatically whenever a Card needs to be converted into a String such as when the card is concatenated onto a string with the operator Thus the statement System out println Your card is the card is equivalent to System out println Your card is the card toString If the card is the queen of hearts either of these will print out Your card is the Queen of Hearts Here is the complete Card class It is general enough to be highly reusable so the work that went into designing writing and testing it pays off handsomely in the long run An object of type Card represents a playing card from a standard Poker deck including Jokers The card has a suit which can be spades hearts diamonds clubs or joker A spade heart diamond or club has one of the 13 values ace 2 3 4 5 6 7 8 9 10 jack queen or king Note that ace is considered to be the smallest value A joker can also have an associated value this value can be anything and can be used to keep track of several different jokers public class Card public final static int SPADES 0 Codes for the 4 suits plus Joker public final static int HEARTS 1 public final static int DIAMONDS 2 public final static int CLUBS 3 public final static int JOKER 4 public final static int ACE 1 Codes for the non numeric cards public final static int JACK 11 Cards 2 through 10 have their public final static int QUEEN 12 numerical values for their codes public final static int KING 13 This card s suit one of the constants SPADES HEARTS DIAMONDS CLUBS or JOKER The suit cannot be changed after the card is constructed private final int suit The card s value For a normal card this is one of the values 1 through 13 with 1 representing ACE For a JOKER the value can be anything The value cannot be changed after the card is constructed private final int value Creates a Joker with 1 as the associated value Note that new Card is equivalent to new Card 1 Card JOKER public Card suit JOKER value 1 Creates a card with a specified suit and value param theValue the value of the new card For a regular card non joker the value must be in the range 1 through 13 with 1 representing an Ace You can use the constants Card ACE Card JACK Card QUEEN and Card KING For

    Original URL path: http://math.hws.edu/javanotes/c5/s4.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 5.5 -- Inheritance, Polymorphism, and Abstract Classes
    an object belonging to any subclass of A The practical effect of this in our example is that an object of type Car can be assigned to a variable of type Vehicle That is it would be legal to say Vehicle myVehicle myCar or even Vehicle myVehicle new Car After either of these statements the variable myVehicle holds a reference to a Vehicle object that happens to be an instance of the subclass Car The object remembers that it is in fact a Car and not just a Vehicle Information about the actual class of an object is stored as part of that object It is even possible to test whether a given object belongs to a given class using the instanceof operator The test if myVehicle instanceof Car determines whether the object referred to by myVehicle is in fact a car On the other hand the assignment statement myCar myVehicle would be illegal because myVehicle could potentially refer to other types of vehicles that are not cars This is similar to a problem we saw previously in Subsection 2 5 6 The computer will not allow you to assign an int value to a variable of type short because not every int is a short Similarly it will not allow you to assign a value of type Vehicle to a variable of type Car because not every vehicle is a car As in the case of ints and shorts the solution here is to use type casting If for some reason you happen to know that myVehicle does in fact refer to a Car you can use the type cast Car myVehicle to tell the computer to treat myVehicle as if it were actually of type Car So you could say myCar Car myVehicle and you could even refer to Car myVehicle numberOfDoors The parentheses are necessary because of precedence The has higher precedence than the type cast so Car myVehicle numberOfDoors would be read as Car myVehicle numberOfDoors an attempt to type cast the int myVehicle numberOfDoors into a Vehicle which is impossible As an example of how this could be used in a program suppose that you want to print out relevant data about the Vehicle referred to by myVehicle If it s a car you will want to print out the car s numberOfDoors but you can t say myVehicle numberOfDoors since there is no numberOfDoors in the Vehicle class But you could say System out println Vehicle Data System out println Registration number myVehicle registrationNumber if myVehicle instanceof Car System out println Type of vehicle Car Car c c Car myVehicle Type cast to get access to numberOfDoors System out println Number of doors c numberOfDoors else if myVehicle instanceof Truck System out println Type of vehicle Truck Truck t t Truck myVehicle Type cast to get access to numberOfAxles System out println Number of axles t numberOfAxles else if myVehicle instanceof Motorcycle System out println Type of vehicle Motorcycle Motorcycle m m Motorcycle myVehicle Type cast to get access to hasSidecar System out println Has a sidecar m hasSidecar Note that for object types when the computer executes a program it checks whether type casts are valid So for example if myVehicle refers to an object of type Truck then the type cast Car myVehicle would be an error When this happens an exception of type ClassCastException is thrown This check is done at run time not compile time because the actual type of the object referred to by myVehicle is not known when the program is compiled 5 5 4 Polymorphism As another example consider a program that deals with shapes drawn on the screen Let s say that the shapes include rectangles ovals and roundrects of various colors A roundrect is just a rectangle with rounded corners Three classes Rectangle Oval and RoundRect could be used to represent the three types of shapes These three classes would have a common superclass Shape to represent features that all three shapes have in common The Shape class could include instance variables to represent the color position and size of a shape and it could include instance methods for changing the values of those properties Changing the color for example might involve changing the value of an instance variable and then redrawing the shape in its new color class Shape Color color must be imported from package java awt void setColor Color newColor Method to change the color of the shape color newColor change value of instance variable redraw redraw shape which will appear in new color void redraw method for drawing the shape what commands should go here more instance variables and methods end of class Shape Now you might see a problem here with the method redraw The problem is that each different type of shape is drawn differently The method setColor can be called for any type of shape How does the computer know which shape to draw when it executes the redraw Informally we can answer the question like this The computer executes redraw by asking the shape to redraw itself Every shape object knows what it has to do to redraw itself In practice this means that each of the specific shape classes has its own redraw method class Rectangle extends Shape void redraw commands for drawing a rectangle possibly more methods and variables class Oval extends Shape void redraw commands for drawing an oval possibly more methods and variables class RoundRect extends Shape void redraw commands for drawing a rounded rectangle possibly more methods and variables Suppose that someShape is a variable of type Shape Then it could refer to an object of any of the types Rectangle Oval or RoundRect As a program executes and the value of someShape changes it could even refer to objects of different types at different times Whenever the statement someShape redraw is executed the redraw method that is actually called is the one appropriate for the type of object to which someShape

    Original URL path: http://math.hws.edu/javanotes/c5/s5.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 7.2 -- Array Processing
    partially full array with just one line of code We can also use Arrays copyOf to decrease the size of a partially full array We might want to do that to avoid having a lot of excess unused spaces To implement this idea the code for deleting player number k from the list of players might become playerList k playerList playerCt 1 playerCt if playerCt playerList length 2 More than half the spaces are empty Cut the array size in half playerList Arrays copyOf playerList playerList length 2 I should mention that class Arrays actually contains a bunch of copyOf methods one for each of the primitive types and one for objects I should also note that when an array of objects is copied it is only pointers to objects that are copied into the new array The contents of the objects are not copied This is the usual rule for assignment of pointers The Arrays class contains other useful methods I ll mention a few of them As with Arrays copyOf there are actually multiple versions of all of these methods for different array types Arrays fill array value Fill an entire array with a specified value The type of value must be compatible with the base type of the array For example assuming that numlist is an array of type double then Arrays fill numlist 17 will set every element of numlist to have the value 17 Arrays fill array fromIndex toIndex value Fills part of the array with value starting at index number fromIndex and ending with index number toIndex 1 Note that toIndex itself is not included Arrays toString array A function that returns a String containing all the values from array separated by commas and enclosed between square brackets The values in the array are converted into strings in the same way they would be if they were printed out Arrays sort array Sorts the entire array To sort an array means to rearrange the values in the array so that they are in increasing order This method works for arrays of String and arrays of primitive type values except for boolean which would be kind of silly But it does not work for all arrays since it must be meaningful to compare any two values in the array to see which is smaller We will discuss array sorting algorithms in Section 7 4 Arrays sort array fromIndex toIndex Sorts just the elements from array fromIndex up to array toIndex 1 Arrays binarySearch array value Searches for value in the array The array must already be sorted into increasing order This is a function that returns an int If the value is found in the array the return value is the index of an element that contains that value If the value does not occur in the array the return value is 1 We will discuss the binary search algorithm in Section 7 4 7 2 3 RandomStrings Revisited One of the examples in Subsection 6 3 2 was a GUI program that shows multiple copies of a message in random positions colors and fonts When the user clicks the program window the positions colors and fonts are changed to new random values Like several other examples from that chapter the program had a flaw It didn t have any way of storing the data that it would need to redraw itself Arrays provide us with one possible solution to this problem We can write a new version of RandomStrings that uses an array to store the position font and color of each string When the panel is painted this information is used to draw the strings so that the panel will paint itself correctly whenever it has to be redrawn When the user clicks the array is filled with new random values and the panel is repainted using the new data So the only time that the picture will change is in response to a mouse click The new version of the program is RandomStringsWithArray java In the program the number of copies of the message is given by a named constant MESSAGE COUNT One way to store the position color and font of MESSAGE COUNT strings would be to use four arrays int x new int MESSAGE COUNT int y new int MESSAGE COUNT Color color new Color MESSAGE COUNT Font font new Font MESSAGE COUNT These arrays would be filled with random values In the paintComponent method the i th copy of the string would be drawn at the point x i y i Its color would be given by color i And it would be drawn in the font font i This would be accomplished by the paintComponent method public void paintComponent Graphics g super paintComponent Fill with background color for int i 0 i MESSAGE COUNT i g setColor color i g setFont font i g drawString message x i y i This approach is said to use parallel arrays The data for a given copy of the message is spread out across several arrays If you think of the arrays as laid out in parallel columns array x in the first column array y in the second array color in the third and array font in the fourth then the data for the i th string can be found along the i th row There is nothing wrong with using parallel arrays in this simple example but it does go against the object oriented philosophy of keeping related data in one object If we follow this rule then we don t have to imagine the relationship among the data because all the data for one copy of the message is physically in one place So when I wrote the program I made a simple class to represent all the data that is needed for one copy of the message An object of this type holds the position color and font of one copy of the string private static class

    Original URL path: http://math.hws.edu/javanotes/c7/s2.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 7.3 -- ArrayList
    not classes and values of primitive type are not objects However sometimes it s useful to treat a primitive value as if it were an object This is true for example when you would like to store primitive type values in an ArrayList You can t do that literally but you can wrap the primitive type value in an object belonging to one of the wrapper classes For example an object of type Double contains a single instance variable of type double The object is a wrapper for the double value You can create an object that wraps the double value 6 0221415e23 with Double d new Double 6 0221415e23 The value of d contains the same information as the value of type double but it is an object If you want to retrieve the double value that is wrapped in the object you can call the function d doubleValue Similarly you can wrap an int in an object of type Integer a boolean value in an object of type Boolean and so on Furthermore to make these classes even easier to use there is automatic conversion between a primitive type and the corresponding wrapper class For example if you use a value of type int in a context that requires an object of type Integer the int will automatically be wrapped in an Integer object If you say Integer answer 42 and the computer will silently read this as if it were Integer answer new Integer 42 This is called autoboxing It works in the other direction too For example if d refers to an object of type Double you can use d in a numerical expression such as 2 d The double value inside d is automatically unboxed and multiplied by 2 Autoboxing and unboxing also apply to subroutine calls For example you can pass an actual parameter of type int to a subroutine that has a formal parameter of type Integer In fact autoboxing and unboxing make it possible in many circumstances to ignore the difference between primitive types and objects This is true in particular for parameterized types Although there is no such thing as ArrayList int there is ArrayList Integer An ArrayList Integer holds objects of type Integer but any object of type Integer really just represents an int value in a rather thin wrapper Suppose that we have an object of type ArrayList Integer ArrayList Integer integerList integerList new ArrayList Integer Then we can for example add an object to integerList that represents the number 42 integerList add new Integer 42 but because of autoboxing we can actually say integerList add 42 and the compiler will automatically wrap 42 in an object of type Integer before adding it to the list Similarly we can say int num integerList get 3 The value returned by integerList get 3 is of type Integer but because of unboxing the compiler will automatically convert the return value into an int as if we had said int num integerList get 3 intValue So in effect we can pretty much use integerList as if it were a dynamic array of int rather than a dynamic array of Integer Of course a similar statement holds for lists of other wrapper classes such as ArrayList Double and ArrayList Character There is one issue that sometimes causes problems A list can hold null values and a null does not correspond to any primitive type value This means for example that the statement int num integerList get 3 can produce a null pointer exception in the case where integerList get 3 returns null Unless you are sure that all the values in your list are non null you need to take this possibility into account 7 3 3 Programming With ArrayList As a simple first example we can redo ReverseWithDynamicArray java from the previous section using an ArrayList instead of a custom dynamic array class In this case we want to store integers in the list so we should use ArrayList Integer Here is the complete program import java util ArrayList Reads a list of non zero numbers from the user then prints out the input numbers in the reverse of the order in which the were entered There is no limit on the number of inputs public class ReverseWithArrayList public static void main String args ArrayList Integer list list new ArrayList Integer System out println Enter some non zero integers Enter 0 to end while true System out print int number TextIO getlnInt if number 0 break list add number System out println System out println Your numbers in reverse are for int i list size 1 i 0 i System out printf 10d n list get i As illustrated in this example ArrayLists are commonly processed using for loops in much the same way that arrays are processed for example the following loop prints out all the items for a variable namelist of type ArrayList String for int i 0 i namelist size i String item namelist get i System out println item You can also use for each loops with ArrayLists so this example could also be written for String item namelist System out println item When working with wrapper classes the loop control variable in the for each loop can be a primitive type variable This works because of unboxing For example if numbers is of type ArrayList Double then the following loop can be used to add up all the values in the list double sum 0 for double num numbers sum sum num This will work as long as none of the items in the list are null If there is a possibility of null values then you will want to use a loop control variable of type Double and test for nulls For example to add up all the non null values in the list double sum for Double num numbers if num null sum sum num Here num is SAFELY unboxed to get a double For

    Original URL path: http://math.hws.edu/javanotes/c7/s3.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 7.5 -- Two-dimensional Arrays
    only have two possible contents It can be alive or dead We will use a 2D array to represent the grid with each element of the array representing the content of one cell in the grid In the game an initial grid is set up in which each cell is marked as either alive or dead After that the game plays itself The grid evolves through a series of time steps The contents of the grid at each time step are completely determined by the contents at the previous time step according to simple rules Each cell in the grid looks at its eight neighbors horizontal vertical and diagonal and counts how many of its neighbors are alive Then the state of the cell in the next step is determined by the rules If the cell is alive in the current time step If the cell has 2 or 3 living neighbors then the cell remains alive in the next time step otherwise it dies A living cell dies of loneliness if it has 0 or 1 living neighbor and of overcrowding if it has more than 3 living neighbors If the cell is dead the current time step If the cell has 3 living neighbors then the cell becomes alive in the next time step otherwise it remains dead Three living cells give birth to a new living cell Here s a picture of part of a Life board showing the same board before and after the rules have been applied The rules are applied to every cell in the grid The picture shows how they apply to four of the cells The Game of Life is interesting because it gives rise to many interesting and surprising patterns Look it up on Wikipedia Here we are just interested in writing a program to simulate the game The complete program can be found in the file Life java In the program the life grid is shown as an array of squares Dead squares are black and living squares are white The program uses MosaicPanel java from Section 4 6 to represent the grid so you will also need that file to compile and run the program In the program you can fill the life board randomly with dead and alive cells or you can use the mouse to set up the game board There is a Step button that will compute one time step of the game and a Start button that will run time steps as an animation We ll look at some of the array processing involved in implementing the Game of Life for this program Since a cell can only be alive or dead it is natural to use a two dimensional array of boolean to represent the states of all the cells The array is named alive and alive r c is true when the cell in row r column c is alive The number of rows and the number of columns are equal and are given by a constant GRID SIZE So for example to fill the Life grid with random values the program uses simple nested for loops for int r 0 r GRID SIZE r for int c 0 c GRID SIZE c Use a 25 probability that the cell is alive alive r c Math random 0 25 Note that the expression Math random 0 25 is a true false value that can be assigned to a boolean array element The array is also used to set the color of the cells on the screen Since the grid of cells is displayed on screen as a MosaicPanel setting the colors is done using the MosaicPanel API Note that the actual drawing is done in the paintComponent method of the MosaicPanel which has its own 2D array of type Color to keep track of the colors of each cell The Life program just has to set the colors in the mosaic This is done in the program in a method named showBoard that is called each time the board changes Again simple nested for loops are used to set the color of each square in the grid for int r 0 r GRID SIZE r for int c 0 c GRID SIZE c if alive r c display setColor r c Color WHITE else display setColor r c null Shows the background color black Of course the most interesting part of the program is computing the new state of the board by applying the rules to the current state The rules apply to each individual cell so again we can use nested for loops to work through all the cells on the board but this time the processing is more complicated Note first that we can t make changes to the values in the array as we work through it since we will need to know the old state of a cell when processing its neighboring cells In fact the program uses a second array to hold the new board as it is being created When the new board is finished it can be substituted for the old board The algorithm goes like this in pseudocode let newboard be a new boolean array for each row r for each column c Let N be the number of neighbors of cell r c in the alive array if N is 3 or N is 2 and alive r c newboard r c true else newboard r c false alive newboard Note that at the end of the process alive is pointing to a new array This doesn t matter as long as the contents of the array represent the new state of the game The old array will be garbage collected The test for whether newboard r c should be true or false might not be obvious but it implements the rules correctly We still need to work on counting the neighbors Consider the cell in row r and column c If it s not at an edge of the board then it s clear where its neighbors are The row above row number r is row number r 1 and the row below is r 1 Similarly for the columns We just have to look at the values of alive r 1 c 1 alive r 1 c alive r 1 c 1 alive r c 1 alive r c 1 alive r 1 c 1 alive r 1 c and alive r 1 c 1 and count the number that are true You should make sure that you understand how the array indexing works here But there is a problem when the cell is along one of the edges of the grid In that case some of the array elements in the list don t exist and an attempt to use them will cause an exception To avoid the exception we have to give special consideration to cells along the edges One idea is that before referencing any array element check that the array element actually exists In that case the code for neighbor counting becomes if r 1 0 c 1 0 alive r 1 c 1 N A cell at position r 1 c 1 exists and is alive if r 1 0 alive r 1 c N A cell at position r 1 c exists and is alive if r 1 0 c 1 GRID SIZE alive r 1 c 1 N A cell at position r 1 c 1 exists and is alive and so on All the possible exceptions are avoided But in my program I actually do something that is common in 2D computer games I pretend that the left edge of the board is attached to the right edge and the top edge to the bottom edge For example for a cell in row 0 we say that the row above is actually the bottom row row number GRID SIZE 1 I use variables to represent the positions above below left and right of a given cell The code turns out to be simpler than the code shown above Here is the complete method for computing the new board private void doFrame Compute the new state of the Life board boolean newboard new boolean GRID SIZE GRID SIZE for int r 0 r GRID SIZE r int above below rows considered above and below row number r int left right columns considered left and right of column c above r 0 r 1 GRID SIZE 1 for see Subsection 2 5 5 below r GRID SIZE 1 r 1 0 for int c 0 c GRID SIZE c left c 0 c 1 GRID SIZE 1 right c GRID SIZE 1 c 1 0 int n 0 number of alive cells in the 8 neighboring cells if alive above left n if alive above c n if alive above right n if alive r left n if alive r right n if alive below left n if alive below c n if alive below right n if n 3 alive r c n 2 newboard r c true else newboard r c false alive newboard Again I urge you to check out the source code Life java and try the program Don t forget that you will also need MosaicPanel java 7 5 3 Checkers As a final example for this chapter we ll look at a more substantial example of using a 2D array This is the longest program that we have encountered so far with 727 lines of code The program lets two users play checkers against each other The checkers game is played on an eight by eight board which is based on an example from Subsection 6 6 5 The players are called red and black after the color of their checkers I m not going to explain the rules of checkers here possibly you can learn them by trying out the program In the program a player moves by clicking on the piece that they want to move move and then clicking on the empty square to which it is to be moved As an aid to the players the squares that the current player can legally click are highlighted The square containing a piece that has been selected to be moved if any is surrounded by a white border Other pieces that can legally be moved are surrounded by a cyan colored border If a piece has has already been selected each empty square that it can legally move to is highlighted with a green border The game enforces the rule that if the current player can jump one of the opponent s pieces then the player must jump When a player s piece becomes a king by reaching the opposite end of the board a big white K is drawn on the piece Here is a picture of the program in the middle of a game It is black s turn to move and the pieces that black can legally move are highlighted with a cyan border The next step is for black to click on one of those pieces I will only cover a part of the programming for this example I encourage you to read the complete source code Checkers java It s long and complex but you should understand all the techniques that it uses with some study The program is a good example of state based event driven object oriented programming The data about the pieces on the board are stored in a two dimensional array Because of the complexity of the program I wanted to divide it into several classes In addition to the main class there are several nested classes One of these classes is CheckersData which handles the data for the board It is mainly this class that I want to talk about The CheckersData class has an instance variable named board of type int The value of board is set to new int 8 8 an 8 by 8 grid of integers The values stored in the grid are defined as constants representing the possible contents of a square on a checkerboard static final int EMPTY 0 Value representing an empty square RED 1 A regular red piece RED KING 2 A red king BLACK 3 A regular black piece BLACK KING 4 A black king The constants RED and BLACK are also used in my program or perhaps misused to represent the two players in the game When a game is started the values in the array are set to represent the initial state of the board The grid of values looks like A regular black piece can only move down the grid That is the row number of the square it moves to must be greater than the row number of the square it comes from A regular red piece can only move up the grid Kings of either color of course can move in both directions One function of the CheckersData class is to take care of all the details of making moves on the board An instance method named makeMove is provided to do this When a player moves a piece from one square to another the values of two elements in the array are changed But that s not all If the move is a jump then the piece that was jumped is removed from the board The method checks whether the move is a jump by checking if the square to which the piece is moving is two rows away from the square where it starts Furthermore a RED piece that moves to row 0 or a BLACK piece that moves to row 7 becomes a king Putting all that into a subroutine is good programming the rest of the program doesn t have to worry about any of these details It just calls this makeMove method Make the move from fromRow fromCol to toRow toCol It is ASSUMED that this move is legal If the move is a jump the jumped piece is removed from the board If a piece moves to the last row on the opponent s side of the board the piece becomes a king void makeMove int fromRow int fromCol int toRow int toCol board toRow toCol board fromRow fromCol Move the piece board fromRow fromCol EMPTY The square it moved from is now empty if fromRow toRow 2 fromRow toRow 2 The move is a jump Remove the jumped piece from the board int jumpRow fromRow toRow 2 Row of the jumped piece int jumpCol fromCol toCol 2 Column of the jumped piece board jumpRow jumpCol EMPTY if toRow 0 board toRow toCol RED board toRow toCol RED KING Red piece becomes a king if toRow 7 board toRow toCol BLACK board toRow toCol BLACK KING Black piece becomes a king end makeMove An even more important function of the CheckersData class is to find legal moves on the board In my program a move in a Checkers game is represented by an object belonging to the following class A CheckersMove object represents a move in the game of Checkers It holds the row and column of the piece that is to be moved and the row and column of the square to which it is to be moved This class makes no guarantee that the move is legal private static class CheckersMove int fromRow fromCol Position of piece to be moved int toRow toCol Square it is to move to CheckersMove int r1 int c1 int r2 int c2 Constructor Set the values of the instance variables fromRow r1 fromCol c1 toRow r2 toCol c2 boolean isJump Test whether this move is a jump It is assumed that the move is legal In a jump the piece moves two rows In a regular move it only moves one row return fromRow toRow 2 fromRow toRow 2 end class CheckersMove The CheckersData class has an instance method which finds all the legal moves that are currently available for a specified player This method is a function that returns an array of type CheckersMove The array contains all the legal moves represented as CheckersMove objects The specification for this method reads Return an array containing all the legal CheckersMoves for the specified player on the current board If the player has no legal moves null is returned The value of player should be one of the constants RED or BLACK if not null is returned If the returned value is non null it consists entirely of jump moves or entirely of regular moves since if the player can jump only jumps are legal moves CheckersMove getLegalMoves int player A brief pseudocode algorithm for the method is Start with an empty list of moves Find any legal jumps and add them to the list if there are no jumps Find any other legal moves and add them to the list if the list is empty return null else return the list Now what is this list We have to return the legal moves in an array But since an array has a fixed size we can t create the array until we know how many moves there are and we don t know that until near the end of the method after we ve already made the list A neat solution is to use an ArrayList instead of an array to hold the moves as we find them In fact I use an object defined by the parameterized type ArrayList CheckersMove so that the list is restricted to holding objects of type CheckersMove As we add moves to the list it will grow just as large as necessary At the end of the method we can create the array that we really want and copy the data into it Let moves be an empty ArrayList CheckersMove Find any legal jumps and add them to moves if moves size is 0

    Original URL path: http://math.hws.edu/javanotes/c7/s5.html (2016-02-07)
    Open archived version from archive