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, Exercises for Chapter 6
    of numbers the sum the mean and the standard deviation Every time the user enters a new number the statistics displayed on the labels should change The user enters a number by typing it into the JTextField and pressing return There should be a Clear button that clears out all the data This means creating a new StatCalc object and resetting the displays on the labels My panel also has an Enter button that does the same thing as pressing the return key in the JTextField Recall that a JTextField generates an ActionEvent when the user presses return so your panel should register itself to listen for ActionEvents from the JTextField as well as the buttons Here is a picture of my solution to this problem See the Solution Exercise 6 8 Write a program that has a JTextArea where the user can enter some text Then program should have a button such that when the user clicks on the button the panel will count the number of lines in the user s input the number of words in the user s input and the number of characters in the user s input This information should be displayed on three labels Recall that if textInput is a JTextArea then you can get the contents of the JTextArea by calling the function textInput getText This function returns a String containing all the text from the text area The number of characters is just the length of this String Lines in the String are separated by the new line character n so the number of lines is just the number of new line characters in the String plus one Words are a little harder to count Exercise 3 4 has some advice about finding the words in a String Essentially you want to count the number of characters that are first characters in words Don t forget to put your JTextArea in a JScrollPane and add the scroll pane to the container not the text area Scrollbars should appear when the user types more text than will fit in the available area Here is a picture of my solution See the Solution Exercise 6 9 A polygon is a geometric figure made up of a sequence of connected line segments The points where the line segments meet are called the vertices of the polygon The Graphics class includes commands for drawing and filling polygons For these commands the coordinates of the vertices of the polygon are stored in arrays If g is a variable of type Graphics then g drawPolygon xCoords yCoords pointCt will draw the outline of the polygon with vertices at the points xCoords 0 yCoords 0 xCoords 1 yCoords 1 xCoords pointCt 1 yCoords pointCt 1 The third parameter pointCt is an int that specifies the number of vertices of the polygon Its value should be 3 or greater The first two parameters are arrays of type int Note that the polygon automatically includes a line from the last

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


  • Javanotes 7.0, Quiz on Chapter 6
    meant by the term event Give at least two different examples of events and discuss how a program might respond to those events Question 2 Explain carefully what the repaint method does Question 3 Java has a standard class called JPanel Discuss two ways in which JPanels can be used Question 4 Draw the picture that will be produced by the following paintComponent method public static void paintComponent Graphics g super paintComponent g for int i 10 i 210 i i 50 for int j 10 j 210 j j 50 g drawLine i 10 j 60 Question 5 Suppose you would like a panel that displays a green square inside a red circle as illustrated Write a paintComponent method for the panel class that will draw the image Question 6 Java has a standard class called MouseEvent What is the purpose of this class What does an object of type MouseEvent do Question 7 One of the main classes in Swing is the JComponent class What is meant by a component What are some examples Question 8 What is the function of a LayoutManager in Java Question 9 Consider the illustration of nested panels from the beginning of Section

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

  • Javanotes 7.0, Section 7.1 -- Array Details
    5 every method in Java had a fixed arity The arity of a method is defined as the number of parameters in a call to the method In a fixed arity method the number of parameters must be the same in every call to the method and must be the same as the number of formal parameters in the method s definition Java 5 introduced variable arity methods In a variable arity method different calls to the method can have different numbers of parameters For example the formatted output method System out printf which was introduced in Subsection 2 4 1 is a variable arity method The first parameter of System out printf must be a String but it can have any number of additional parameters of any types Calling a variable arity method is no different from calling any other sort of method but writing one requires some new syntax As an example consider a method that can compute the average of any number of values of type double The definition of such a method could begin with public static double average double numbers Here the after the type name double is what makes this a variable arity method It indicates that any number of values of type double can be provided when the subroutine is called so that for example average 1 4 9 16 average 3 14 2 17 average 0 375 and even average are all legal calls to this method Note that actual parameters of type int can be passed to average The integers will as usual be automatically converted to real numbers When the method is called the values of all the actual parameters that correspond to the variable arity parameter are placed into an array and it is this array that is actually passed to the method That is in the body of a method a variable arity parameter of type T actually looks like an ordinary parameter of type T The length of the array tells you how many actual parameters were provided in the method call In the average example the body of the method would see an array named numbers of type double The number of actual parameters in the method call would be numbers length and the values of the actual parameters would be numbers 0 numbers 1 and so on A complete definition of the method would be public static double average double numbers Inside this method numbers if of type double double sum The sum of all the actual parameters double average The average of all the actual parameters sum 0 for int i 0 i numbers length i sum sum numbers i Add one of the actual parameters to the sum average sum numbers length return average By the way it is possible to pass a single array to a variable arity method instead of a list of individual values For example suppose that salesData is a variable of type double Then it would be legal

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

  • Javanotes 7.0, Section 7.4 -- Searching and Sorting
    d where w is a word and d is its definition A general association list is a list of pairs k v where k is some key value and v is a value associated to that key In general we want to assume that no two pairs in the list have the same key There are two basic operations on association lists Given a key k find the value v associated with k if any And given a key k and a value v add the pair k v to the association list replacing the pair if any that had the same key value The two operations are usually called get and put Association lists are very widely used in computer science For example a compiler has to keep track of the location in memory associated with each variable It can do this with an association list in which each key is a variable name and the associated value is the address of that variable in memory Another example would be a mailing list if we think of it as associating an address to each name on the list As a related example consider a phone directory that associates a phone number to each name We ll look at a highly simplified version of this example This is not meant to be a realistic way to implement a phone directory The items in the phone directory s association list could be objects belonging to the class class PhoneEntry String name String phoneNum The data for a phone directory consists of an array of type PhoneEntry and an integer variable to keep track of how many entries are actually stored in the directory The technique of dynamic arrays Subsection 7 2 4 can be used in order to avoid putting an arbitrary limit on the number of entries that the phone directory can hold Using an ArrayList would be another possibility A PhoneDirectory class should include instance methods that implement the get and put operations Here is one possible simple definition of the class A PhoneDirectory holds a list of names with a phone number for each name It is possible to find the number associated with a given name and to specify the phone number for a given name public class PhoneDirectory An object of type PhoneEntry holds one name number pair private static class PhoneEntry String name The name String number The associated phone number private PhoneEntry data Array that holds the name number pairs private int dataCount The number of pairs stored in the array Constructor creates an initially empty directory public PhoneDirectory data new PhoneEntry 1 dataCount 0 Looks for a name number pair with a given name If found the index of the pair in the data array is returned If no pair contains the given name then the return value is 1 This private method is used internally in getNumber and putNumber private int find String name for int i 0 i dataCount i if data i name equals name return i The name has been found in position i return 1 The name does not exist in the array Finds the phone number if any for a given name return The phone number associated with the name if the name does not occur in the phone directory then the return value is null public String getNumber String name int position find name if position 1 return null There is no phone entry for the given name else return data position number Associates a given name with a given phone number If the name already exists in the phone directory then the new number replaces the old one Otherwise a new name number pair is added The name and number should both be non null An IllegalArgumentException is thrown if this is not the case public void putNumber String name String number if name null number null throw new IllegalArgumentException name and number cannot be null int i find name if i 0 The name already exists in position i in the array Just replace the old number at that position with the new data i number number else Add a new name number pair to the array If the array is already full first create a new larger array if dataCount data length data Arrays copyOf data 2 data length PhoneEntry newEntry new PhoneEntry Create a new pair newEntry name name newEntry number number data dataCount newEntry Add the new pair to the array dataCount end class PhoneDirectory The class defines a private instance method find that uses linear search to find the position of a given name in the array of name number pairs The find method is used both in the getNumber method and in the putNumber method Note in particular that putNumber name number has to check whether the name is in the phone directory If so it just changes the number in the existing entry if not it has to create a new phone entry and add it to the array This class could use a lot of improvement For one thing it would be nice to use binary search instead of simple linear search in the getNumber method However we could only do that if the list of PhoneEntries were sorted into alphabetical order according to name In fact it s really not all that hard to keep the list of entries in sorted order as you ll see in the next subsection I will mention that association lists are also called maps and Java has a standard parameterized type name Map that implements association lists for keys and values of any type You will encounter this class in Chapter 10 7 4 3 Insertion Sort We ve seen that there are good reasons for sorting arrays There are many algorithms available for doing so One of the easiest to understand is the insertion sort algorithm This technique is also applicable to the problem of keeping a list in

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

  • Javanotes 7.0, Exercises for Chapter 7
    class for the three classes Since all three types of art use a random gray background the background color can be defined in their superclass The superclass also contains a draw method that draws the picture this is an abstract method because its implementation depends on the particular type of art that is being drawn The abstract class can be defined as private abstract class ArtData Color backgroundColor The background color for the art ArtData Constructor sets background color to be a random gray int x int 256 Math random backgroundColor new Color x x x abstract void draw Graphics g Draws this artwork Each of the three subclasses of ArtData must define its own draw method It must also define instance variables to hold the data necessary to draw the picture I suggest that you should create random data for the picture in the constructor of the class so that constructing the object will automatically create the data for the random artwork One problem with this is that you can t create the data until you know the size of the panel so you can t create an ArtData object in the constructor of the panel One solution is to create an ArtData object at the beginning of the paintComponent method if the object has not already been created In each of the three subclasses you will need to use one or more arrays or ArrayLists to store the data See the Solution Exercise 7 7 Write a program that will read a text file selected by the user and will make an alphabetical list of all the different words in that file All words should be converted to lower case and duplicates should be eliminated from the list The list should be written to an output file selected by the user As discussed in Subsection 2 4 4 you can use TextIO to read and write files Use a variable of type ArrayList String to store the words It is not easy to separate a file into words as you are reading it You can use the following method Read the next word from TextIO if there is one First skip past any non letters in the input If an end of file is encountered before a word is found return null Otherwise read and return the word A word is defined as a sequence of letters Also a word can include an apostrophe if the apostrophe is surrounded by letters on each side return the next word from TextIO or null if an end of file is encountered private static String readNextWord char ch TextIO peek Look at next character in input while ch TextIO EOF Character isLetter ch Skip past non letters TextIO getAnyChar Read the character ch TextIO peek Look at the next character if ch TextIO EOF Encountered end of file return null At this point we know the next character is a letter so read a word String word This will be the

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

  • Javanotes 7.0, Quiz on Chapter 7
    a dynamic array over a regular array Question 6 What does it mean to say that ArrayList is a parameterized type Question 7 Suppose that a variable strlst has been declared as ArrayList String strlst new ArrayList String Assume that the list is not empty and that all the items in the list are non null Write a code segment that will find and print the string in the list that comes first in lexicographic order Question 8 Show the exact output produced by the following code segment char pic new char 6 6 for int i 0 i 6 i for int j 0 j 6 j if i j i 0 i 5 pic i j else pic i j for int i 0 i 6 i for int j 0 j 6 j System out print pic i j System out println Question 9 Write a complete static method that finds the largest value in an array of ints The method should have one parameter which is an array of type int The largest number in the array should be returned as the value of the method Question 10 Suppose that temperature measurements were made on each day of 2014 in each of 100 cities The measurements have been stored in an array int temps new int 100 365 where temps c d holds the measurement for city number c on the d th day of the year Write a code segment that will print out the average temperature over the course of the whole year for each city The average temperature for a city can be obtained by adding up all 365 measurements for that city and dividing the answer by 365 0 Question 11 Suppose that a class Employee is defined as follows class Employee

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

  • Javanotes 7.0, Section 8.1 -- Introduction to Correctness and Robustness
    are insignificant in FORTRAN so this is equivalent to DO20I 1 5 On the other hand the command DO20I 1 5 with a period instead of a comma is an assignment statement that assigns the value 1 5 to the variable DO20I Supposedly the inadvertent substitution of a period for a comma in a statement of this type caused a rocket to blow up on take off Because FORTRAN doesn t require variables to be declared the compiler would be happy to accept the statement DO20I 1 5 It would just create a new variable named DO20I If FORTRAN required variables to be declared the compiler would have complained that the variable DO20I was undeclared While most programming languages today do require variables to be declared there are other features in common programming languages that can cause problems Java has eliminated some of these features Some people complain that this makes Java less efficient and less powerful While there is some justice in this criticism the increase in security and robustness is probably worth the cost in most circumstances The best defense against some types of errors is to design a programming language in which the errors are impossible In other cases where the error can t be completely eliminated the language can be designed so that when the error does occur it will automatically be detected This will at least prevent the error from causing further harm and it will alert the programmer that there is a bug that needs fixing Let s look at a few cases where the designers of Java have taken these approaches An array is created with a certain number of locations numbered from zero up to some specified maximum index It is an error to try to use an array location that is outside of the specified range In Java any attempt to do so is detected automatically by the system In some other languages such as C and C it s up to the programmer to make sure that the index is within the legal range Suppose that an array A has three locations A 0 A 1 and A 2 Then A 3 A 4 and so on refer to memory locations beyond the end of the array In Java an attempt to store data in A 3 will be detected The program will be terminated unless the error is caught as discussed in Section 3 7 In C or C the computer will just go ahead and store the data in memory that is not part of the array Since there is no telling what that memory location is being used for the result will be unpredictable The consequences could be much more serious than a terminated program See for example the discussion of buffer overflow errors later in this section Pointers are a notorious source of programming errors In Java a variable of object type holds either a pointer to an object or the special value null Any attempt to use a null value as if it were a pointer to an actual object will be detected by the system In some other languages again it s up to the programmer to avoid such null pointer errors In my old Macintosh computer a null pointer was actually implemented as if it were a pointer to memory location zero A program could use a null pointer to change values stored in memory near location zero Unfortunately the Macintosh stored important system data in those locations Changing that data could cause the whole system to crash a consequence more severe than a single failed program Another type of pointer error occurs when a pointer value is pointing to an object of the wrong type or to a segment of memory that does not even hold a valid object at all These types of errors are impossible in Java which does not allow programmers to manipulate pointers directly In other languages it is possible to set a pointer to point essentially to any location in memory If this is done incorrectly then using the pointer can have unpredictable results Another type of error that cannot occur in Java is a memory leak In Java once there are no longer any pointers that refer to an object that object is garbage collected so that the memory that it occupied can be reused In other languages it is the programmer s responsibility to return unused memory to the system If the programmer fails to do this unused memory can build up leaving less memory for programs and data There is a story that many common programs for older Windows computers had so many memory leaks that the computer would run out of memory after a few days of use and would have to be restarted Many programs have been found to suffer from buffer overflow errors Buffer overflow errors often make the news because they are responsible for many network security problems When one computer receives data from another computer over a network that data is stored in a buffer The buffer is just a segment of memory that has been allocated by a program to hold data that it expects to receive A buffer overflow occurs when more data is received than will fit in the buffer The question is what happens then If the error is detected by the program or by the networking software then the only thing that has happened is a failed network data transmission The real problem occurs when the software does not properly detect buffer overflows In that case the software continues to store data in memory even after the buffer is filled and the extra data goes into some part of memory that was not allocated by the program as part of the buffer That memory might be in use for some other purpose It might contain important data It might even contain part of the program itself This is where the real security issues come

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

  • Javanotes 7.0, Section 8.4 -- Assertions and Annotations
    If you are correct in your belief that the method is never called with illegal arguments then checking the conditions in the assertions would be unnecessary If your belief is not correct the problem should turn up during testing or debugging when the program is run with the assertions enabled If the root method is part of a software library that you expect other people to use then the situation is less clear Oracle s Java documentation advises that assertions should not be used for checking the contract of public methods If the caller of a method violates the contract by passing illegal parameters then an exception should be thrown This will enforce the contract whether or not assertions are enabled However while it s true that Java programmers expect the contract of a method to be enforced with exceptions there are reasonable arguments for using assertions instead in some cases One might say that assertions are for you to help you in debugging your code while exceptions are for people who use your code to alert them that they are misusing it On the other hand it never hurts to use an assertion to check a postcondition of a method A postcondition is something that is supposed to be true after the method has executed and it can be tested with an assert statement at the end of the method If the postcondition is false there is a bug in the method itself and that is something that needs to be found during the development of the method To have any effect assertions must be enabled when the program is run How to do this depends on what programming environment you are using See Section 2 6 for a discussion of programming environments In the usual command line environment assertions are enabled by adding the option enableassertions to the java command that is used to run the program For example if the class that contains the main program is RootFinder then the command java enableassertions RootFinder will run the program with assertions enabled The enableassertions option can be abbreviated to ea so the command can alternatively be written as java ea RootFinder In fact it is possible to enable assertions in just part of a program An option of the form ea class name enables only the assertions in the specified class Note that there are no spaces between the ea the and the name of the class To enable all the assertions in a package and in its sub packages you can use an option of the form ea package name To enable assertions in the default package that is classes that are not specified to belong to a package like almost all the classes in this book use ea For example to run a Java program named MegaPaint with assertions enabled for every class in the packages named paintutils and drawing you would use the command java ea paintutils ea drawing MegaPaint If you are using the

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