Download FREE Sample Here

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Solutions to Exercises (Chapters 1 through 4)
Dawn Ellis and Frank M. Carrano
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Chapter 1 Exercises
1.
What is volatile and nonvolatile memory?
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.
2.
Name three input and three output devices.
Input devices: mouse, keyboard, scanner
Output devices: printer, monitor, and speakers
4.
Define a memory address.
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.
5.
What is a binary numeral?
A binary numeral is a sequence of bits. A bit can have the value of either a 1 or a 0.
6.
What is the decimal equivalent of the following binary numbers? 10110,
11001, 10101
10110 = 2 4  2 2  21  16  4  2  22
11001  2 4  2 3  2 0  16  8  1  25
10101  2 4  2 2  2 0  16  4  1  21



Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
7.
Java is a multiplatform programming language. What does this statement
mean?
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.
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Chapter 2 Exercises
1.
What are the three categories of Java identifiers? Give an example of
each category.
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
2.
Is programming style, such as indentation, a requirement of the Java
language?
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.
3.
Write statements to display the following phrase exactly as shown:
To be or
not to be
System.out.println("To be or");
System.out.println("not to be");
4.
Write statements to display the following phrase in one line of output.
To be or
not to be
System.out.println("To be or not to be");
5.
What is the difference between the // comment notation and the /* */
comment notation?
The // notation represents a single line comment and the /* */ notation represents a
comment that spans several lines.
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
6.
What is the purpose of the Javadoc utility? Give an example of a
Javadoc utility comment.
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.
*/
7.
What primitive data type would you use to represent the most precise
real number?
double
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?
double salesTaxRate;
salesTaxRate = .0925;
double salesTax = 19.95 * salesTaxRate;
The value of salesTax is 1.845375.
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.
System.out.println("Sales tax:" + salesTax);
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);
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Length: 5.0
Width: 8.5
Area: 42.5
11.
Which of the following are literals?
count, ‘a’, 7.5, letter, 10, salesTax
‘a’, 7.5,
12.
and 10
Write a statement to declare a named constant for a sales tax rate of
7.5%.
final double salesTaxRate = .075;
13.
Why is it good practice to use named constants, as opposed to using
literals?
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.
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?
next()
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.
System.out.print("Enter the sales tax rate: ");
Scanner keyboard = new Scanner(System.in);
double rate = keyboard.nextDouble();
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
16.
Write an application that prints the following pattern:
*
**
***
****
*****
*****
****
***
**
*
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("*");
}
}
17.
Write an application that prompts for your name, address, birthday and
hobby. Display each on separate lines, properly labeled.
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();
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
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);
}
}
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Chapter 3 Exercises
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
a.
b.
c.
d.
e.
18
15
10
-1
0
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
a.
b.
c.
d.
4.0
4
5.33
5
3.
Explain how to use Java to determine whether x is an odd integer.
int result = x % 2;
If result is not equal to
4.
zero, then x is an odd integer.
Write two different Java statements that each compute the cube of an
integer x.
result = x * x * x;
result = Math.pow(x, 3);
result = Math.cbrt(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;
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
a.
b.
c.
d.
e.
f.
6.
legal
illegal
legal
legal
illegal
illegal
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
a.
b.
c.
d.
e.
f.
double
double
long
float
double
long
7.
Using Zellers congruence algorithm, determine the day of the week for
March 17, 2020.
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.
8.
For each of the following mathematical expressions, write a Java
expression to represent it.
64
a.
17
b.
e1
c.
23
 d.
62
e.




Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
a.
b.
c.
d.
e.
9.
Math.sqrt(64)
Math.abs(-17)
Math.exp(-1)
Math.cbrt(2)
Math.pow(6, 2)
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
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));
}
}
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.
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);
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
System.out.print(fahrenheitTemp + " degrees Fahrenheit equals ");
System.out.println(celsiusTemp + " degrees Celsius");
}
}
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
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
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
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
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
System.out.println("The first second
System.out.println("The remainder is
System.out.println();
System.out.println("If the remainder
"is a multiple of
} // end main
} // end Multiple
is " + first + ".");
is " + second + ".");
" + multiple + ".");
is 0, the first number " +
the second number.");
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Chapter 4 Exercises
1.
What does it mean to instantiate an object?
Instantiating an object is simply the process of creating a new instance of a class type.
This is usually accomplished using the new operator.
2.
What is a reference variable? How does it relate to an alias?
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.
3.
Display the following tabbed heading by using one println statement.
Name
Address
City
State
Zip
System.out.println("Name\tAddress\tCity\tState\tZip");
4.
In the expression one.concat(two), what object is the receiving
object?
The receiving object is one.
5.
What do the following statements display?
String data = "54 Long Street";
Scanner scan = new Scanner(data);
System.out.println(scan.next());
54
6.
What is the difference in meaning between the following two statements?
import java.util.Date;
import java.util.*;
The first statement only imports the class Date from the java.util package. The second
statement imports the entire java.util package.
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
7.
a.
b.
c.
8.
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.
Date aDateObject = new Date();
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;
String date = aDateObject.toString();
String time = aDateObject.substring(8, 19);
When constructing a BigDecimal object, why is it desirable to pass the
constructor a string that represents the numeric value?
You write the desired value of the BigDecimal object as a string to preserve its accuracy.
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?
a.
b.
c.
BigDecimal(String val, MathContext mc)
floatValue()
movePointLeft(int n)
10.
Why is the method equals provided for the wrapper classes in the Java
Class Library?
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.
11.
Complete the following table of maximum and minimum values for the
wrapper classes:
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Wrapper
Class MAX_VALUE
MIN_VALUE
Byte
Character
Double
Float
Integer

Long
Short
2 7 1
2 7

Wrapper Class
Byte
Character
Double
Float
Integer
Long
Short
12.
MAX_VALUE
MIN_VALUE
2 1
2 7
7
/uFFFF
2  2  2
52

1023
(2  223 )
 2127
2 31 1
2 63 1 
215 1 
/u0000
21074
2149
2 31
2 63
215







After consulting the online documentation forthe class JOptionPane
in the Java Class Library, describe the differences among the methods
showConfirmDialog, showInputDialog, and showMessageDialog.
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.
13.
Given a Random object called rand, what does the call
rand.nextDouble() return?
A pseudorandom, uniformly distributed, double value between 0.0 and 1.0 will be
returned.
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));
17
17
23
15.
Why must numeric input read from an input dialog box be parsed?
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
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.
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.
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
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.
import java.util.Scanner;
public class UpperCase
{
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
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 ".
Full file at http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
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
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]”.
19.
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);
}
}
20.
Full fileaatprogram
http://testbank360.eu/solution-manual-imagine-java-programming-1st-edition-frank-carran
Write
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.
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));
}
}