Solutions to Exercises (Chapters 1 through...

20
Solutions to Exercises (Chapters 1 through 4) Dawn Ellis and Frank M. Carrano

Transcript of Solutions to Exercises (Chapters 1 through...

Page 1: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Solutions to Exercises (Chapters 1 through 4) Dawn Ellis and Frank M. Carrano

Page 2: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Chapter 1 Exercises

Volatile is a property of primary memory whereas nonvolatile is a property of secondary memory. Primary memory is volatile because when the power to the computer system is interrupted, the contents of primary memory are lost. Secondary memory is nonvolatile because when the power to the computer system is interrupted, the contents in secondary memory remain.

Input devices: mouse, keyboard, scanner Output devices: printer, monitor, and speakers

A memory address is a numerical reference to a physical byte within a computer systems primary memory. The designers of the computer system fix this address. The address cannot be changed, but the contents in which the address refers can be changed.

A binary numeral is a sequence of bits. A bit can have the value of either a 1 or a 0.

10110 =

!

24 + 22 + 21 =16 + 4 + 2 = 22 11001

!

= 24 + 23 + 20 =16 + 8 +1= 25 10101

!

= 24 + 22 + 20 =16 + 4 +1= 21

1. What is volatile and nonvolatile memory?

2. Name three input and three output devices.

4. Define a memory address.

5. What is a binary numeral?

6. What is the decimal equivalent of the following binary numbers? 10110, 11001, 10101

Page 3: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Java source code is compiled into a file containing byte code when is interpreted by the Java Virtual Machine. The Java Virtual Machine is designed to run on many different operating systems, making a Java a platform independent language.

7. Java is a multiplatform programming language. What does this statement mean?

Page 4: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Chapter 2 Exercises

Identifiers fall into one of three categories: identifiers that we invent, identifiers that another programmer has chosen, and identifiers that are part of the Java language. Identifiers we invent: sample, args Identifiers invented by others: System, out, println, main Identifiers included in the Java language: public, static, void, class

Programming style is not a requirement of the Java language. Although it is good to develop a basic style that uses white space, brace alignment and indentation to make the program easy for the human reader.

System.out.println("To be or"); System.out.println("not to be");

System.out.println("To be or not to be");

The // notation represents a single line comment and the /* */ notation represents a comment that spans several lines.

1. What are the three categories of Java identifiers? Give an example of each category.

2. Is programming style, such as indentation, a requirement of the Java language?

3. Write statements to display the following phrase exactly as shown: To be or not to be

4. Write statements to display the following phrase in one line of output. To be or not to be

5. What is the difference between the // comment notation and the /* */ comment notation?

Page 5: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

The Javadoc utility produces an HTML document that describes the classes and methods that use the Javadoc comment. /** This is a javadoc comment. It can span several lines. */

double

double salesTaxRate; salesTaxRate = .0925; double salesTax = 19.95 * salesTaxRate;

The value of salesTax is 1.845375.

System.out.println("Sales tax:" + salesTax);

6. What is the purpose of the Javadoc utility? Give an example of a Javadoc utility comment.

7. What primitive data type would you use to represent the most precise real number?

8. Write a statement to declare a variable to represent the sales tax percentage. Write a second statement to assign the variable the value of 9.25%. Then write a statement that computes the sales tax on a purchase of $19.95 and stores the result in a properly declared variable called salesTax. What is the value of salesTax?

9. Write a statement that displays the label “Sales tax:” and appends the calculated value from the previous exercise to the end of the label.

10. When the following sequence of statements executes, what is displayed?

double length = 5.0; double width = 8.5; System.out.println("Length: " + length); System.out.println("Width: " + width); System.out.print("Area: ");

System.out.println(length * width);

Page 6: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Length: 5.0 Width: 8.5 Area: 42.5

‘a’, 7.5, and 10

final double salesTaxRate = .075;

Named constants not only make a program more readable, but it also drastically reduces the chance of an error in the value of the constant that could be introduced if the literal value is used instead.

next()

System.out.print("Enter the sales tax rate: "); Scanner keyboard = new Scanner(System.in); double rate = keyboard.nextDouble();

11. Which of the following are literals? count, ‘a’, 7.5, letter, 10, salesTax

12. Write a statement to declare a named constant for a sales tax rate of 7.5%.

13. Why is it good practice to use named constants, as opposed to using literals?

14. Consult the documentation of the Java class library for the Scanner class. What method would you use to read a string from a Scanner object?

15. Write a statement that asks the user to enter the sales tax rate. Write statements to create a Scanner object, and then use it to read and store the rate as a real number.

Page 7: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

public class Pattern { public static void main(String[] args) { System.out.println("*"); System.out.println("**"); System.out.println("***"); System.out.println("****"); System.out.println("*****"); System.out.println("*****"); System.out.println("****"); System.out.println("***"); System.out.println("**"); System.out.println("*"); } }

import java.util.*; /* This program prompts for your name, address, birthday and hobby, then displays each on separate lines, properly labeled. */ public class AboutYou { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String name, streetAddress, city, state, zip, birthday, hobby; //Collect all the inputs System.out.print("Enter your name: "); name = keyboard.nextLine();

16. Write an application that prints the following pattern: * ** *** **** ***** ***** **** *** ** *

17. Write an application that prompts for your name, address, birthday and hobby. Display each on separate lines, properly labeled.

Page 8: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

System.out.print("Enter your street address: "); streetAddress = keyboard.nextLine(); System.out.print("Enter your city: "); city = keyboard.nextLine(); System.out.print("Enter your state: "); state = keyboard.nextLine(); System.out.print("Enter your zip: "); zip = keyboard.nextLine(); System.out.print("Enter your birthday: "); birthday = keyboard.nextLine(); System.out.print("Enter your favorite hobby: "); hobby = keyboard.nextLine(); //Display the inputs to the user System.out.println(); System.out.println("Name: " + name); System.out.println("Address: " + streetAddress); System.out.println("City: " + city); System.out.println("State: " + state); System.out.println("Zip: " + zip); System.out.println("Birthday: " + birthday); System.out.println("Hobby: " + hobby); } }

Page 9: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Chapter 3 Exercises

a. 18 b. 15 c. 10 d. -1 e. 0

a. 4.0 b. 4 c. 5.33 d. 5

int result = x % 2; If result is not equal to zero, then x is an odd integer.

result = x * x * x; result = Math.pow(x, 3); result = Math.cbrt(x);

1. What is the value of each of the following expressions? a. 17 + 2 – 5 / 52 + 3 * 5 – 2 b. 3 * 2 / 3 + 8 c. 6 / 2 * 3 – 10 d. 6 % 2 * 10

2. What is the value of each of the following expressions? a. 12 / 3.0 b. 12 / 3 c. 16.0 / 3 d. 16 / 3

3. Explain how to use Java to determine whether x is an odd integer.

4. Write two different Java statements that each compute the cube of an integer x.

5. Classify the following Java statements as either legal or illegal. Let b, s, i, l, f, and d represent variables of type byte, short, int, long, float, and double.

a. d = l; b. l = f; c. i = b; d. i = s; e. b = s; f. i = d;

Page 10: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

a. legal b. illegal c. legal d. legal e. illegal f. illegal

a. double b. double c. long d. float e. double f. long

m = 3 d = 17 y = 2020 f = d + [(26 * (m + 1)) / 10] + y + [y / 4] + 6[y / 100] + [y /400] f = 17 + [(26 * (3 + 1))/ 10] + 2020 + [2020/4] + 6[2020/100] + [2020 / 400] f = 2677 w = f % 7 w = 3 3/17/2020 falls on a Tuesday.

6. What is the data type of each of the following expressions if i, l, f, and d represent variables of type int, long, float, and double?

a. f + d b. d * i c. l – i d. i / f e. l % d f. l * l

7. Using Zellers congruence algorithm, determine the day of the week for March 17, 2020.

8. For each of the following mathematical expressions, write a Java expression to represent it. a.

!

64 b.

!

"17 c.

!

e"1 d.

!

23 e.

!

62

Page 11: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

a. Math.sqrt(64) b. Math.abs(-17) c. Math.exp(-1) d. Math.cbrt(2) e. Math.pow(6, 2)

public class MakeTable { public static void main(String[] args) { System.out.println("X\tY\tMin(x, y)"); System.out.println("10\t5\t" + Math.min(10, 5)); System.out.println("23\t13\t" + Math.min(23, 13)); System.out.println("100\t100\t" + Math.min(100, 100)); System.out.println("-1\t-5\t" + Math.min(-1, -5)); System.out.println("0\t-8\t" + Math.min(0, -8)); } }

import java.util.*; public class TempConverter { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); double celsiusTemp, fahrenheitTemp; System.out.print("Enter the temperature to convert: "); fahrenheitTemp = keyboard.nextDouble(); celsiusTemp = (5.0/9.0) * (fahrenheitTemp - 32.0);

9. Write a program that displays the following table. Use the method Math.min to compute the smaller of x and y in each case.

X Y Min(x, y) 10 5 5 13 23 13 100 100 100 -1 -5 -5 0 -8 -8

10. Write a program to convert a user-supplied temperature from Fahrenheit to Celsius using the following formula. If C represents a temperature in degrees Celsius, and F represents a temperature in degrees Fahrenheit, then C = 5 x (F – 32) / 9.

Page 12: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

System.out.print(fahrenheitTemp + " degrees Fahrenheit equals "); System.out.println(celsiusTemp + " degrees Celsius"); } }

import java.util.Scanner; public class Ticket { public static void main(String[] args) { // describe problem System.out.println("Is your ticket a winner " + "(a multiple of 6)?\n"); // get input Scanner keyboard = new Scanner(System.in); System.out.print("Enter your ticket number: "); int ticket = keyboard.nextInt(); // compute winning ticket numbers int winner = ticket % 6; // display results System.out.println(); System.out.println("The ticket number " + ticket + " has a remainder of " + winner + "."); System.out.println(); System.out.println("If the remainder is 0, you are a winner!"); } // end main } // end Ticket

11. In a contest, a ticket number wins a prize if it is a multiple of 6. Write a program that reads a ticket number and indicates whether it is a winner. The program’s output could appear as follows:

Sample Output 1 Is your ticket a winner? Enter your ticket number: 12

The ticket number 12 is a winner if the following value is zero: 0 Sample Output 2

Is your ticket a winner? Enter your ticket number: 37 The ticket number 37 is a winner if the following value is zero: 1

Page 13: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

import java.util.Scanner; public class Multiple { public static void main(String[] args) { // describe problem System.out.println("This program determines whether one " + "number is a multiple of a second number.\n"); // get input Scanner keyboard = new Scanner(System.in); System.out.print("Enter your first integer number: "); int first = keyboard.nextInt(); System.out.print("Enter your second integer number: "); int second = keyboard.nextInt(); // compute winning ticket numbers int multiple = first % second; // display results System.out.println(); System.out.println("The first number is " + first + "."); System.out.println("The first second is " + second + "."); System.out.println("The remainder is " + multiple + "."); System.out.println(); System.out.println("If the remainder is 0, the first number " + "is a multiple of the second number."); } // end main } // end Multiple

12. One integer is a multiple of another integer if the remainder after dividing the first integer by the second is zero. Write a program that tests whether one integer is a multiple of a second integer. The program’s output could appear as follows:

Sample Output 1 A test of whether one integer is a multiple of a second integer.

Enter the first integer: 25 Enter the second integer: 5 25 is a multiple of 5 if the following value is zero: 0 Sample Output 2 A test of whether one integer is a multiple of a second integer. Enter the first integer: 23 Enter the second integer: 7 23 is a multiple of 7 if the following value is zero: 2

Page 14: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Chapter 4 Exercises

Instantiating an object is simply the process of creating a new instance of a class type. This is usually accomplished using the new operator.

A reference variable is a variable of a class type. A reference variable contains the memory address of the object it refers to. An alias is simply an object with multiple references.

System.out.println("Name\tAddress\tCity\tState\tZip");

The receiving object is one.

54

The first statement only imports the class Date from the java.util package. The second statement imports the entire java.util package.

1. What does it mean to instantiate an object?

2. What is a reference variable? How does it relate to an alias?

3. Display the following tabbed heading by using one println statement. Name Address City State Zip

4. In the expression one.concat(two), what object is the receiving object?

5. What do the following statements display?

String data = "54 Long Street"; Scanner scan = new Scanner(data); System.out.println(scan.next());

6. What is the difference in meaning between the following two statements?

import java.util.Date; import java.util.*;

Page 15: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

a. Date aDateObject = new Date(); b. String date = aDateObject.toString(); String month = date.substring(3, 6); String day = date.substring(6, 8); String year = date.substring(19); String datePortion = month + " " + day + ", " + year; c. String date = aDateObject.toString(); String time = aDateObject.substring(8, 19);

You write the desired value of the BigDecimal object as a string to preserve its accuracy.

a. BigDecimal(String val, MathContext mc) b. floatValue() c. movePointLeft(int n)

The equals method is provided not only for the wrapper classes in Java but for other classes as well. The equals method allows one to compare two objects to determine if their data components are equivalent.

7. Write statements that a. Define a Date object. b. Define a string that contains only the date portion of the Date

object. For example, if the string representation of the Date object is "WedJul3016:19:38EDT2010", define the string

"Jul 30, 2010". c. Define a string that contains only the time portion of the Date.

object.

8. When constructing a BigDecimal object, why is it desirable to pass the constructor a string that represents the numeric value?

9. By consulting the online documentation of the Java Class Library for the class BigDecimal, answer the following questions.

a. What constructor would you use to construct a BigDecimal object from a string that is rounded toward positive infinity?

b. What method would you use to convert a BigDecimal object to a floating-point value?

c. What method would you use to move the decimal point of a BigDecimal object two places to the left?

10. Why is the method equals provided for the wrapper classes in the Java Class Library?

Page 16: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

Wrapper Class MAX_VALUE MIN_VALUE Byte

!

27 "1

!

"27 Character /uFFFF /u0000 Double

!

2 " 2"52( ) # 21023

!

2"1074

Float

!

(2 " 2"23) # 2127

!

2"149 Integer

!

231 "1

!

"231 Long

!

263 "1

!

"263 Short

!

215 "1

!

"215

The showConfirmDialog method presents a dialog box that asks a confirming question such as yes, no, or cancel. The showInputDialog method presents a dialog box that accepts input. The showMessageDialog method presents a dialog box that relays a message.

A pseudorandom, uniformly distributed, double value between 0.0 and 1.0 will be returned.

17 17 23

11. Complete the following table of maximum and minimum values for the wrapper classes:

Wrapper Class MAX_VALUE MIN_VALUE Byte

!

27 "1

!

"27 Character Double Float Integer Long Short

12. After consulting the online documentation for the class JOptionPane in the Java Class Library, describe the differences among the methods showConfirmDialog, showInputDialog, and showMessageDialog.

13. Given a Random object called rand, what does the call rand.nextDouble() return?

14. What do the following statements display? System.out.println(Integer.parseInt("17")); System.out.println(Integer.parseInt("17", 10)); System.out.println(Integer.parseInt("17", 16));

15. Why must numeric input read from an input dialog box be parsed?

Page 17: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

The input dialog reads all data provided by the user as a string. If we were collecting numeric data for computations, the string must be parsed into the correct format before being used in any computation, otherwise, we would get unexpected results. For example, suppose a dialog box was provided to enter two floating-point values to be summed. When the plus sign appears between two strings, concatenation occurs.

import java.util.Scanner; public class StringDemoEx16 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Please type your first name, a space, and " + "your last name: "); String firstName = keyboard.next(); String lastName = keyboard.next(); int nameLength = firstName.length() + lastName.length(); char firstInitial = firstName.charAt(0); char lastInitial = lastName.charAt(0); String initials = firstInitial + ". " + lastInitial + "."; System.out.println("Hi, " + firstName + " " + lastName + ".\nYour name contains " + nameLength + " characters."); System.out.println("Your first name is " + firstName + "."); System.out.println("Your last name is " + lastName + "."); System.out.println("Your initials are " + initials); } // end main } // end StringDemoEx16

import java.util.Scanner; public class UpperCase {

16. The program in Listing 4-1 uses the method nextLine to read the first and last names of a person. Revise the program using the method next instead of nextLine to read the first and last names into separate variables. Your revised program should produce the same output as the original program in Listing 4-1.

17. Many programs convert the information provided by the user to a consistent format. For example, we could require all data that is read to be converted to uppercase. Create a Java program that reads, converts to uppercase, and displays a person’s name and full address.

Page 18: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); //Collect the information System.out.println("Please type your name: "); String name = keyboard.nextLine(); name = name.trim(); System.out.println("Please type your street address: "); String streetAddress = keyboard.nextLine(); streetAddress = streetAddress.trim(); System.out.println("Please type your city: "); String city = keyboard.nextLine(); city = city.trim(); System.out.println("Please type your state: "); String state = keyboard.nextLine(); state = state.trim(); System.out.println("Please type your zip code: "); String zipCode = keyboard.nextLine(); zipCode = zipCode.trim(); //Convert the information name = name.toUpperCase(); streetAddress = streetAddress.toUpperCase(); city = city.toUpperCase(); state = state.toUpperCase(); //Display the information System.out.println(name); System.out.println(streetAddress); System.out.println(city + ", " + state + " " + zipCode); } }

18. Write a program that displays a tree, such as the following one, using text characters:

/\ / \ / \ / \ / \ ------------ "" "" "" Remember to use escape sequences to display the characters \ and the ".

Page 19: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

public class Tree { public static void main(String[] args) { System.out.println(" /\\"); System.out.println(" / \\"); System.out.println(" / \\"); System.out.println(" / \\"); System.out.println(" / \\"); System.out.println(" ------------------"); System.out.println(" \" \""); System.out.println(" \" \""); System.out.println(" \" \""); } // end main } // end Tree

import javax.swing.JOptionPane; import java.util.Scanner; public class Extractor { public static void main(String[] args) {

String extractionString = JOptionPane.showInputDialog( "Enter a string containing an email address:");

//Scan the string for spaces; the 5th space should be the //start of the email address Scanner scan = new Scanner(extractionString); scan.useDelimiter("\\s"); String email = scan.next(); email = scan.next(); email = scan.next(); email = scan.next(); email = scan.next(); JOptionPane.showMessageDialog(null, "Email address: " + email); System.exit(0); } }

19. Write a Java program using the methods of the class JOptionPane to read a string containing an e-mail address. The string must begin as “My e-mail address is ” and be followed by an e-mail address. Extract the e-mail address from the string using methods of the class Scanner, and display it using the methods of the class JOptionPane. Demonstrate that only [email protected] is extracted from the string “My e-mail address is [email protected]”.

Page 20: Solutions to Exercises (Chapters 1 through 4)40p6zu91z1c3x7lz71846qd1-wpengine.netdna-ssl.com/...Dawn Ellis and Frank M. Carrano . Chapter 1 Exercises Volatile is a property of primary

import java.util.Random; import java.util.Scanner; import java.text.DecimalFormat; public class MyRandomGenerator { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter a seed for the random number " + "generator: "); long seed = keyboard.nextLong(); //Seed the generator Random generator = new Random(seed); //Generate 5 random numbers double firstNumber = generator.nextDouble(); double secondNumber = generator.nextDouble(); double thirdNumber = generator.nextDouble(); double fourthNumber = generator.nextDouble(); double fifthNumber = generator.nextDouble(); DecimalFormat formatter = new DecimalFormat("0.0000"); System.out.println("Five random numbers in the range of 0.0 " + "to 1.0:"); System.out.println(formatter.format(firstNumber)); System.out.println(formatter.format(secondNumber)); System.out.println(formatter.format(thirdNumber)); System.out.println(formatter.format(fourthNumber)); System.out.println(formatter.format(fifthNumber)); } }

20. Write a program that generates and displays five random numbers within the range 0.0 to 1.0. Allow the user to provide the seed. Display the random numbers with four digits after the decimal point.