Java Software Solutions Chapters 5, 6, 7

Ace your homework & exams now with Quizwiz!

5.15 Write an equals method for the Die class of Section 4.2. The method should return true if the Die object it is invoked on has the same facevalue as the Die object passed as a parameter, otherwise it should return false.

//------------------------------------------------------ // Returns true if this Die equals die, otherwise // returns false. //------------------------------------------------------ public boolean equals(Die die) { return (this.faceValue == die.faceValue); }

7.24 The Num class is defined in Section 7.7. Overload the constructor of that class by defining a second constructor which takes no parameters and sets the value attribute to zero.

//------------------------------------------------------ // Sets up the new Num object, storing a default value // of 0. //------------------------------------------------------ public Num () { value = 0; }

6.5 What is the difference between a conditional operator and a conditional statement?

6.5 The conditional operator is a trinary operator that evaluates a condition and produces one of two possible results. A conditional statement, such as the if and switch statements, is a category of statements that allow conditions to be evaluated and the appropriate statements executed as a result.

5.9 How do block statements help us in the construction of conditionals?

A block statement groups several statements together. We use them to define the body of an if statement or loop when we want to do multiple things based on the boolean condition

7.10 Describe a dependency relationship between two classes.

A dependency relationship between two classes occurs when one class relies on the functionality of the other. It is often referred to as a "uses" relationship.

6.12 When would we use a for loop instead of a while loop?

A for loop is usually used when we know, or can calculate, how many times we want to iterate through the loop body. A while loop handles a more generic situation.

7.11 Explain how a class can have an association with itself.

A method executed through an object might take as a parameter another object created from the same class. For example, the concat method of the String class is executed through one String object and takes another String object as a parameter.

5.10 What is a nested if statement?

A nested if occurs when the statement inside an if or else clause is an if statement. A nested if lets the programmer make a series of decisions. Similarly, a nested loop is a loop within a loop.

5.5 What is a truth table?

A truth table is a table that shows all possible results of a boolean expression, given all possible combinations of variables and conditions.

6.8 Compare and contrast a while loop and a do loop.

A while loop evaluates the condition first. If it is true, it executes the loop body. The do loop executes the body first and then evaluates the condition. Therefore, the body of a while loop is executed zero or more times, and the body of a do loop is executed one or more times.

5.27 What type of elements does an ArrayList hold?

An ArrayList generally holds references to the Object class, which means that it can hold any type of object at all (this is discussed further in Chapter 8). A specific type of element can and should be specified in the ArrayList declaration to restrict the type of objects that can be added and eliminate the need to cast the type when extracted.

5.26 What are the advantages of using an ArrayList object?

An ArrayList stores and manages multiple objects at one time. It allows you to access the objects by a numeric index and keeps the indexes of its objects continuous as they are added and removed. An ArrayList dynamically increases its capacity as needed.

7.12 What is an aggregate object?

An aggregate object is an object that has other objects as instance data. That is, an aggregate object is one that is made up of other objects.

6.4 Transform the following nested if statement into an equivalent switch statement. if (num1 == 5) myChar = 'W'; else if (num1 == 6) myChar = 'X'; else if (num1 == 7) myChar = 'Y'; else myChar = 'Z';

An equivalent switch statement is: switch (num1) { case 5: myChar = 'W'; break; case 6: myChar = 'X'; break; case 7: myChar = 'Y'; break; default: myChar = 'Z'; }

5.17 What is an infinite loop? Specifically, what causes it?

An infinite loop is a repetition statement that never terminates. Specifically, the body of the loop never causes the condition to become false.

5.28 Write a declaration for a variable named dice that is an ArrayList of Die objects.

ArrayList<Die> dice = new ArrayList<Die>();

7.8 Assume you are defining a BankAccount class whose objects each represent a separate bank account. Write a declaration for a variable of the class that will hold the minimum balance that each account must maintain.

Assuming that the minimum required is 100 and you decide to use the identifier MIN_BALANCE, the declaration is: public static final int MIN_BALANCE = 100;

5.4 Given the following declarations, what is the value of each of thelisted boolean expressions? int value1 = 5, value2 = 10; boolean done = true; a. value1 <= value2 b. (value1 + 5) >= value2 c. value1 < value2 / 2 d. value2 != value1 e. !(value1 == value2) f. (value1 < value2) || done g. (value1 > value2) || done h. (value1 < value2) && !done i. done || !done j. ((value1 > value2) || done) && (!done || (value2 > value1))

Assuming the given declarations, the values are: a. true, b. true, c. false, d. true, e. true, f. true, g. true, h. false, i. true, j. true

7.7 Assume you are defining a BankAccount class whose objects each represent a separate bank account. Write a declaration for a variable of the class that will hold the combined total balance of all the bank accounts represented by the class.

Assuming you decide to use the identifier totalBalance, the declaration is: private static int totalBalance = 0;

7.19 Answer the following questions about the PigLatinTranslator class. a. No constructor is defined. Why not? b. Some of the defined methods are private. Why? c. A Scanner object is declared in the translate method. What is it used to scan?

Based on the PigLatinTranslator class: a. The service provided by the class, namely to translate a string into Pig Latin, is accessed through a static method. Therefore, there is no need to create an object of the class. It follows that there is no need for a constructor. b. The methods defined as private methods do not provide services directly to clients of the class. Instead, they are used to support the public method translate. c. The Scanner object declared in the translate method is used to scan the string sentence, which is passed to the method by the client.

5.11 For each assumption, what output is produced by the following code fragment?

Based on the given assumptions, the output would be: a. red orange white yellow b. black blue green c. yellow green

5.8 What output is produced by the following code fragment given the assumptions below? if (num1 < num2) System.out.print (" red "); if ((num1 + 5) < num2) System.out.print (" white "); else System.out.print (" blue "); System.out.println (" yellow "); a. Assuming the value of num1 is 2 and the value of num2 is 10? b. Assuming the value of num1 is 10 and the value of num2 is 2? c. Assuming the value of num1 is 2 and the value of num2 is 2?

Based on the given assumptions, the output would be: a. red white yellow b. blue yellow c. blue yellow

5.13 Why must we be careful when comparing floating point values for equality?

Because they are stored internally as binary numbers, comparing floating point values for exact equality will be true only if they are the same bit-by-bit. It's better to use a reasonable tolerance value and consider the difference between the two values.

5.2 What type of conditions are conditionals and loops based on?

Each conditional and loop is based on a boolean condition that evaluates to either true or false.

7.4 How can identifying the nouns in a problem specification help you design an object-oriented solution to the problem?

Identifying the nouns in a problem specification can help you identify potential classes to use when developing an object-oriented solution to a problem. The nouns in the specification often correspond to objects that should be represented in the solution.

6.2 What happens if a case in a switch statement does not end with a break statement?

If a case does not end with a break statement, processing continues into the statements of the next case. We usually want to use break statements in order to jump to the end of the switch.

6.3 What is the output of the GradeReport program if the user enters "72"? What if the user enters "46"? What if the user enters "123"?

If the user enters 72, the output is: That grade is average. If the user enters 46, the output is: That grade is not passing. If the user enters 123, the output is: That grade is not passing.

7.5 Is it important to identify and define all of the methods that a class will contain during the early stages of problem solution design? Discuss.

It is not crucial to identify and define all the methods that a class will contain during the early stages of problem solution design. It is often sufficient to just identify those methods that provide the primary responsibilities of the class. Additional methods can be added to a class as needed, when you evolve and add detail to your design.

7.6 What is the difference between a static variable and an instance variable?

Memory space for an instance variable is created for each object that is instantiated from a class. A static variable is shared among all objects of a class.

7.18 What is method decomposition?

Method decomposition is the process of dividing a complex method into several support methods to get the job done. This simplifies and facilitates the design of the program.

7.21 How are objects passed as parameters?

Objects are passed to methods by copying the reference to the object (its address). Therefore, the actual and formal parameters of a method become aliases of each other.

7.22 How are overloaded methods distinguished from each other?

Overloaded methods are distinguished by having a unique signature, which includes the number, order, and type of the parameters. The return type is not part of the signature.

6.11 Write a do loop to obtain a sequence of positive integers from the user, using zero as a sentinel value. The program should output the sum of the numbers.

Scanner scan = new Scanner (System.in); int num, sum = 0; do { System.out.print ("enter next number (0 to quit) > "); num = scan.nextInt (); sum += num; } while (num != 0); System.out.println (sum);

5.20 What output is produced by the following code fragment? int low = 0, high = 10; while (low <= high) { System.out.println (low); high = high − low; }

Since the value of high always remains larger than the value of low, the code loops continuously, producing many lines of zeros, until the program is terminated.

7.3 Compare and contrast the four basic development activities presented in this section with the five general problem-solving steps presented in Section 1.6.

Software development is a problem-solving activity. Therefore, it is not surprising that the four basic development activities presented in this section are essentially the same as the five general problem-solving steps presented in Section 1.6. "Establishing the requirements" directly corresponds to "understanding the problem." "Designing a solution" and "considering alternative designs" taken together correspond to "creating a design"--in the case of software, the design is the solution. Finally, in both approaches we include "implementation" and "testing" stages.

6.7 Express the following logic in a succinct manner using the conditional operator. if (val <= 10) System.out.println ("The value is not greater than 10."); else System.out.println ("The value is greater than 10.");

System.out.println ("The value is " + ((val <= 10) ? "not" : "") + "greater than 10.");

6.10 What output is produced by the following code fragment? int low = 10, high = 0; do { System.out.println (low); low++; } while (low <= high);

The code contains an infinite loop. The numbers 10, 11, 12, and so on will be printed until the program is terminated or until the number gets too large to be held by the int variable low.

5.3 What are the equality operators? The relational operators? The logical operators?

The equality operators are equal (==) and not equal (!=). The relational operators are less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=). The logical operators are not (!), and (&&) and or (||).

5.1 What is meant by the flow of control through a program?

The flow of control through a program determines the program statements that will be executed on a given run of the program.

5.25 Assume the Scanner object fileScan has been initialized to read from a file. Write a while loop that calculates the average number of characters per line of the file.

The following code prints out the average number of characters per line: int numChars = 0; int numLines = 0; String holdLine; // Read and process each line of the file while (fileScan.hasNext()) { numLines++; holdLine = fileScan.nextLine(); numChars += holdLine.length(); } System.out.println ((double)numChars/numLines);

7.1 Name the four basic activities that are involved in a software development process.

The four basic activities in software development are requirements analysis (deciding what the program should do), design (deciding how to do it), implementation (writing the solution in source code), and testing (validating the implementation).

5.19 What output is produced by the following code fragment? int low = 10, high = 0; while (low <= high) { System.out.println (low); low++; }

The loop is not entered, so there is no output

7.9 What kinds of variables can the main method of any program reference? Why?

The main method of any program is static, and can refer only to static or local variables. Therefore, a main method could not refer to instance variables declared at the class level.

5.18 What output is produced by the following code fragment? int low = 0, high = 10; while (low < high) { System.out.println (low); low++; }

The output is the integers 0 through 9, printed one integer per line.

6.9 What output is produced by the following code fragment? int low = 0, high = 10; do { System.out.println (low); low++; } while (low < high);

The output is the integers 0 through 9, printed one integer per line.

6.15 What output is produced by the following code fragment? int value = 6; for (int num = 1; num <= value; num ++) { for (int i = 1; i <= (value — num); i++) System.out.print (" "); for (int i = 1; i <= ((2 * num) — 1); i++) System.out.print ("*"); System.out.println (); }

The output is: * *** ***** ******* ********* ***********

5.21 What output is produced by the following code fragment? int low = 0, high = 10, mid; while (low <= high) { mid = low; while (mid <= high) { System.out.print (mid + " "); mid++; } System.out.println (); low++; }

The output is: 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 3 4 5 6 7 8 9 10 4 5 6 7 8 9 10 5 6 7 8 9 10 6 7 8 9 10 7 8 9 10 8 9 10 9 10 10

6.13 What output is produced by the following code fragment? int value = 0; for (int num = 10; num <= 40; num += 10) { value = value + num; } System.out.println (value);

The output is: 100

6.14 What output is produced by the following code fragment? int value = 0; for (int num = 10; num < 40; num += 10) { value = value + num; } System.out.println (value);

The output is: 60

7.20 Identify the resultant sequence of calls/returns of PigLatinTranslator support methods when translate is invoked with the following actual parameters. a. "animal" b. "hello" c. "We are the champions"

The sequence of calls is: a. translate - translateWord - beginsWithVowel b. translate - translateWord - beginsWithVowel - beginsWithBlend c. translate - translateWord - beginsWithVowel-beginsWithBl end - translateWord - beginsWithVowel - translateWord - beginsWithVowel - beginsWithBlend - translateWord - beginsWithVowel - beginsWithBlend

7.13 What does the this reference refer to?

The this reference always refers to the currently executing object. A non-static method of a class is written generically for all objects of the class, but it is invoked through a particular object. The this reference, therefore, refers to the object through which that method is currently being executed.

7.25 Select the term from the following list that best matches each of the following phrases: black-box, defects, regression, review, test case, test suite, walkthrough, white-box a. Running previous test cases after a change is made to a program to help ensure that the change did not introduce an error. b. A meeting in which several people collectively evaluate an artifact. c. A review that steps carefully through a document, evaluating each section. d. The goal of testing is to discover these.

The word that best matches is a. regression b. review c. walkthrough d. defects e. test case f. test suite g. black-box h. white-box

7.2 Who creates/specifies software requirements, the client or the developer? Discuss.

Typically the client provides an initial set of requirements or a description of a problem they would like to have solved. It is the responsibility of the software developer to work with the client to make sure the requirements or problem statement is correct and unambiguous.

5.14 How do we compare strings for equality?

We compare strings for equality using the equals method of the String class, which returns a boolean result. The compareTo method of the String class can also be used to compare strings. It returns a positive, 0, or negative integer result depending on the relationship between the two strings.

6.1 When a Java program is running, what happens if the expression evaluated for a switch statement does not match any of the case values associated with the statement?

When a Java program is running, if the expression evaluated for a switch statement does not match any of the case values associated with the statement, execution continues with the default case. If no default case exists, processing continues with the statement following the switch statement.

5.29 What output is produced by the following code fragment? ArrayList<String> names = new ArrayList<String>(); names.add ("Andy"); names.add ("Betty"); names.add (1, "Chet"); names.add (1, "Don"); names.remove (2); System.out.println (names);

[Andy, Don, Betty]

5.24 Devise statements that create each of the following Scanner objects. a. One for interactive input, which reads from System.in . b. One that reads from the file "info.dat". c. One that reads from the String variable infoString .

a. Scanner user = new Scanner (System.in); b. Scanner infoFileScan = new Scanner (new File("info.dat")); c. Scanner infoStringScan = new Scanner (infoString);

7.23 For each of the following pairs of method headers, state whether or not the signatures are distinct. If not, explain why not. a. String describe (String name, int count) String describe (int count, String name) b. void count ( ) int count ( ) c. int howMany (int compareValue) int howMany (int ceiling) d. boolean greater (int value1) boolean greater (int value1, int value2)

a. They are distinct. b. They are not distinct. The return type of a method is not part of its signature. c. They are not distinct. The names of a method's parameters are not part of its signature. d. They are distinct.

6.6 Write a declaration that initializes a char variable named id to 'A' if the boolean variable first is true and to 'B' otherwise.

char id = (first) ? 'A' : 'B';

6.16 Assume die is a Die object (as defined in Section 4.2). Write a code fragment that will roll die 100 times and output the average value rolled.

final int NUMROLLS = 100; int sum = 0; for (int i = 1; i <= NUMROLLS; i++) { sum += die.roll(); } System.out.println((double)sum/NUMROLLS);

5.16 Assume the String variables s1 and s2 have been initialized. Write an expression that prints out the two strings on separate lines in lexicographic order.

if (s1.compareTo(s2) < 0) System.out.println (s1 + "\n" + s2); else System.out.println (s2 + "\n" + s1);

5.12 Write an expression that will print a message based on the value of the int variable named temperature. If temperature is equal to or less than 50, it prints "It is cool." on one line and "Dress warmly." on the next. If temperature is greater than 80, it prints "It is warm." on one line and "Dress coolly." on the next. If temperature is in between 50 and 80, it prints "It is pleasant." on one line and "Dress pleasantly." on the next.

if (temperature <= 50) { System.out.println ("It is cool."); System.out.println ("Dress warmly."); } else if (temperature > 80) { System.out.println ("It is warm."); System.out.println ("Dress cooly."); } else { System.out.println ("It is pleasant."); System.out.println ("Dress pleasantly."); }

5.22 Assume the int variable value has been initialized to a positive integer. Write a while loop that prints all of the positive divisors of value. For example, if value is 28, it prints divisors of 28: 1 2 4 7 14 28

int count = 1; System.out.print ("divisors of " + value + ":"); while (count <= value) { if ((value % count) == 0) System.out.print(" " + count); count++; }

5.23 Assume the int variable value has been initialized to a positive integer. Write a while loop that prints all of the positive divisors of each number from one to value . For example, if value is 4, it prints divisors of 1: 1 divisors of 2: 1 2 divisors of 3: 1 3 divisors of 4: 1 2 4

int count1 = 1, count2; while (count1 <= value) { System.out.print ("divisors of " + count1 + ":"); count2 = 1; while (count2 <= count1) { if ((count1 % count2) == 0) System.out.print(" " + count2); count2++; } System.out.println (); count1++; }


Related study sets

Chapter 5-ENTR-202-Small Business: Paths to Part-Time Entrepreneurship

View Set

Medical Surgical Questions for Exam 3

View Set

Market Revolution, Andrew Jackson, and Reform

View Set

EAQ Chapter 3 Legal and Ethical Aspects of Nursing

View Set

Module 4 Chapter 12 - Anatomy & Physiology

View Set

Chapter 28 Psychiatric Emergencies

View Set

BIO 190 DSM/Mastering Biology Ch. 9

View Set