Chapter 1
1. a. False; b. False; c. True; d. False; e. False; f; True; g. True; h. False; i. False; j. True; k. False; l. True.
3. Monitor and printer.
5.An operating system monitors the overall activity of the computer and provides services. Some of these services include memory management, input/output activities, and storage management.
7.In machine language the programs are written using the binary codes while in high-level language the program are closer to the natural language. For execution, a high-level language program is translated into the machine language while a machine language need not be translated into any other language.
9. Syntax errors.
11. Instructions in a high level language are closer to the natural language, such as English, and therefore, are easier to understand and learn than the machine language.
13. To find the weighted average of the four test scores, first you need to know each test score and its weight. Next, you multiply each test score with its weight, and then add these numbers to get the average. Therefore,
- Get testScore1, weightTestScore1
- Get testScore2, weightTestScore2
- Get testScore3, weightTestScore3
- Get testScore4, weightTestScore4
- weightedAverage = testScore1 * weightTestScore1 +
testScore2 * weightTestScore2 +
testScore3 * weightTestScore3 +
testScore4 * weightTestScore4;
15. To calculate the selling price of an item, we need to know the original price (the price the store pays to buy) of the item. We can then the use the following formula to find the selling price:
sellingPrice = (originalPrice + originalPrice × 0.80) × 0.90
The algorithm is as follows:
- Get originalPrice
- Calculate the sellingPrice using the formula:
sellingPrice = (originalPrice + originalPrice × 0.80) × 0.90
The information needed to calculate the selling price is the original price and the marked-up percentage.
17.Suppose that numOfPages denotes the number of pages to be faxed and billingAmount denotes the total charges for the pages faxed. To calculate the total charges, you need to know the number of pages faxed.
If numOfPages is less than or equal to ten, the billing amount is service charges plus (numOfPages×0.20); otherwise, billing amount is service charges plus 10×0.20plus (numOfPages-10)×0.10.
You can now write the algorithm as follows:
a. Get numOfPages.
b.Calculate billing amount using the formula:
if (numOfPagesis less than or equal to 10)
billingAmount = 3.00 + (numOfPages × 0.20);
otherwise
billingAmount = 3.00 + 10 × 0.20 + (numOfPages - 10) × 0.10;
Chapter 2
1. a. False; b. False; c. False; d. False; e. True; f. True; g. True; h. False; i. True; j. False;
3. a
5.The identifiers firstName and FirstName are not the same. Java is case sensitive. The first character offirstName is lowercase f while the first character of FirstName is uppercase F. So these identifiers are different.
7. a. 3; b. 0.5; c. 4.5; d. 38.5; e. 1; f. 2; g. 2; h. 420.0;
9.7
11. a and c are valid
13.a.32 * a + b
b.'8'
c."Julie Nelson"
d. (b * b – 4 * a * c) / (2 * a)
e.(a + b) / c * (e * f) – g * h
f. (–b + (b * b – 4 * a * c)) / (2 * a)
15. x = 20
y = 15
z = 6
w = 11.5
t = 4.5
17. a. x = 2, y = 5, z = 6
b. x + y = 7
c. Sum of 2 and 6 is 8
d. z / x = 3
e. 2 times 2 = 4
19. a. System.out.println(); or System.out.print("\n"); or
System.out.print('\n');
b. System.out.println("\t");
c.System.out.println("\"");
21. a. firstName
b. discountedPrice
c. numOfJuiceBottles
d. milesTravelled
e. highestTestScore
23.A correct answer is:
publicclassExercise23
{
staticfinalint SECRET_NUM = 11213;
staticfinaldouble PAY_RATE = 18.35;
publicstaticvoid main(String[] arg)
{
int one, two, three;
double first, second;
double paycheck, hoursWorked;
one = 18;
two = 11;
three = 3;
first = 25;
second = first * three;
second = 2 * SECRET_NUM;
System.out.println(first + " " + second + " " + SECRET_NUM);
hoursWorked = 35;
paycheck = hoursWorked * PAY_RATE;
System.out.println("Wages = " + paycheck);
}
}
25. A correct answer is:
publicclassExercise25
{
staticfinalcharSTAR = '*';
staticfinalint PRIME = 71;
publicstaticvoid main(String[] arg)
{
int count = 1;
int sum = count + PRIME;
double x = 25.67;
int newNum = count * PRIME + 2;
sum = sum + count;
x = x + sum * count;
System.out.println(" count = " + count + ", sum = "
+ sum + ", PRIME = " + PRIME);
}
}
27. The classString is contained in the package java.lang. You do not need to import classes from the package java.lang. The system automatically does it for you.
29. a. x = x + 5 – z;
b. y = y * (2 * x + 5 – z);
c. w = w + 2 * z + 4;
d. x = x – (z + y – t);
e. sum = sum + num;
f. x = x / (y – 2);
31.
a b c sum
sum = a + b + (int)c; 3 5 14.1 22
c /= a; 3 5 4.7 22
b += (int)c – a; 3 6 4.7 22
a *= 2 * b + (int)c; 48 6 4.7 22
33. (NOTE: The user input is shaded.)
Enter last name: Miller
Enter a two digit number: 34
Enter a positive integer less than 1000: 340
Name: Miller
Id: 3417
Mystery number: 3689
35. The program requires three inputs. One possible form of input is:
number
string
number
Another possible form of input is:
number string
number
Chapter 3
1. a. False; b. True; c. True; d. True;
3. An object is an instance of a specific class.
5.str = new String("Java Programming");
7.TheclassString is contained in the package java.lang. If a program uses a class contained in this package, the Java system automatically imports that class. Therefore, becauseclassStringis contained in the package java.lang, it is not necessary to explicitly import this class using the import statement.
9. a.Going
b.amusement
c.GOING TO THE AMUSEMENT PARK
d.going to the amusement park
e.Going *o *he amusemen* park
11. a. false
b.true
13.name = console.nextLine();
15. This statement causes the following input dialog box to appear that allows the user to enter the score.
[FIG]Chapter 3 Exercise 15
17. JOptionPane.showMessageDialog(null,
"Current Temperature: 70 degrees",
"Temperature",
19.x = console.nextInt();
ch = console.next().charAt(0);
y = console.nextInt();
21.java.io
23.acctNumber = infile.nextInt();
accountType = infile.next();
balance = infile.nextDouble();
25. a. Same as before.
b. The file contains the output produced by the program.
c. The file contains the output produced by the program. Old contents are erased.
d. The program would prepare the file and store the output in the file.
Chapter 4
1. a. True; b. False; c. False; d. False; e. False; f. False; g. False; h. False; i. True;
3.a. true; b. false; c. true; d. true; e. true
5.100 200 0
7. Omit the semicolon afterelse.
if (score >= 60)
System.out.println("You pass.");
else
System.out.println("You fail.");
9. 31
11. 1 3
13.if (0 < overSpeed& overSpeed <= 5)
fine = 20.00;
else if (5 < overSpeedoverSpeed <= 10)
fine = 75.00;
elseif (10 < overSpeedoverSpeed <= 15)
fine = 150.00;
elseif (overSpeed > 15)
fine = 150.00 + 20.00 * (overSpeed – 15);
15. a. (i) The output is: Grade is C. The value of score after the if statement executes is 70.
(ii) The expression score = 70in statement (ii), will result in a syntax error.
b. (i) No output. The value of score after the if statement executes is 80.
(ii) The expression score = 70in statement (ii), will result in a syntax error.
17. a. if (x < 5)
y = 10;
else
y = 20;
b. if(fuel >= 10)
drive = 150;
else
drive = 30;
c. if(booksBought >= 3)
discount = 0.15;
else
discount = 0.0;
19.a is invalid: The expression n <= 2 evaluates to a boolean value, which is not an integral type. The expression in the switch expression must evaluate to an integral value. b Invalid: Acase value cannot appear more than once. c, and d are valid.
21. 7
23. There is more than one answer. One possible answer is:
import java.util.*;
public class Errors
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int a, b;
int c;
boolean found;
System.out.print("Enter the first integer: ");
a = console.nextInt();
System.out.println();
System.out.print("Enter the second integer: ");
b = console.nextInt();
if (a > a * b & 10 < b)
found = 2 * a > b;
else
{
found = 2 * a < b;
if (found)
a = 3;
c = 15;
if (b > 0)
{
b = 0;
a = 1;
}
}
}
}
25. a. true; b. true; c. false; d. true
Chapter 5
1.a. False; b. True; c. False; d. True; e. True; f. True; g. True; h. False;
3. 5
5.When ch > 'Z'
7.Sum = 158
9.Sum = 158
11. 11 18 25
13. Replace the while loop statement with the following:
while (response == 'Y' || response == 'y')
Replace the output statement:
System.out.printf("%.2f + %.2f = %.2f %n",
num1, num2, (num1 - num2));
with the following:
System.out.printf("%.2f + %.2f = %.2f %n",
num1, num2, (num1 + num2));
15. 4 3 2 1
17. 0 3 8 15 24
19. Loop control variable: j
The initialization statement: j = 1;
Loop condition: j <= 10;
Update statement: j++
The statement that updates the value of s: s = s + j * (j – 1);
21. 2 7 17 37 77 157
23. a. *
b. infinite loop
c. infinite loop
d. ****
e. ******
f. ***
25.The relationship between x and y is: 3y = x.
Output:x = 19683, y = 10
27.
0 - 24
25 - 49
50 - 74
75 - 99
100 - 124
125 - 149
150 - 174
175 – 200
29.a. Both; b.do...while; c.while; d. while
31.In a pretest loop, the loop condition is evaluated before executing the body of the loop. In a posttest loop, the loop condition is evaluated after executing the body of the loop. A posttest loop executes at least once, while a pretest loop may not execute at all.
33.(Assume that console is a Scanner object initialized to the standard input device.)
int num;
do
{
System.out.println("Enter a number less than 20 "
+ "or greater than 75: ");
num = console.nextInt();
}
while (20 <= num & num <= 75);
35. int i = 0, value = 0;
do
{
if (i % 2 == 0 & i <= 10)
value = value + i * i;
elseif (i % 2 == 0 & i > 10)
value = value + i;
else
value = value - i;
i = i + 1;
}
while (i <= 20);
System.out.println("value = " + value);
The output is: value = 200
37. number = console.nextInt();
while (number != -1)
{
total = total + number;
number = console.nextInt();
}
39. a.
number = 1;
while (number <= 10)
{
System.out.print(number + " ");
number++;
}
System.out.println();
b.
number = 1;
do
{
System.out.print(number + " ");
number++;
}
while (number <= 10);
System.out.println();
41. 11 18 25
43-1 0 3 8 15 24
45.12 11 9 7 6 4 2 1
Chapter 6
1. a. True; b. True; c. True; d. True; e. False; f; False; g. True; h. True; i. True; j. False; k. False; l. False;
3. JTextField.
5. To identify other GUI components such as a JTextField.
7. Through the process outlined, you have methodology which will allow you to critically think and plan you problem solving approach. You may be able to identify the flaws involved in your thinking before you implement it. A well-analyzed problem leads to a well designed algorithm. Also, a program that is well-analyzed is easier to modify and spot and fix errors. No one will build a house without a blueprint.
9.
//Program: Determine the sum and product of two numbers.
import javax.swing.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
publicclass SumProduct extends JFrame
{
private JLabel firstL, secondL, sumL, productL;
private JTextField firstTF, secondTF, sumTF, productTF;
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
privatestaticfinalint WIDTH = 400;
privatestaticfinalint HEIGHT = 300;
public SumProduct()
{
//Create four labels
firstL = new JLabel("Enter the first number: ",
SwingConstants.RIGHT);
secondL = new JLabel("Enter the second number: ",
SwingConstants.RIGHT);
sumL = new JLabel("Sum: ", SwingConstants.RIGHT);
productL = new JLabel("Product: ",
SwingConstants.RIGHT);
//Create four textfields
firstTF = new JTextField(10);
secondTF = new JTextField(10);
sumTF = new JTextField(10);
productTF = new JTextField(10);
//Create Calculate Button
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//Create Exit Button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
//Set the title of the window
setTitle("Sum and Product Calculation");
//Get the container
Container pane = getContentPane();
//Set the layout
pane.setLayout(new GridLayout(5, 2));
//Place the components in the pane
pane.add(firstL);
pane.add(firstTF);
pane.add(secondL);
pane.add(secondTF);
pane.add(sumL);
pane.add(sumTF);
pane.add(productL);
pane.add(productTF);
pane.add(calculateB);
pane.add(exitB);
//set the size of the window and display it
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
privateclass CalculateButtonHandler
implements ActionListener
{
publicvoid actionPerformed(ActionEvent e)
{
double second, first, sum, product;
first = Double.parseDouble(firstTF.getText());
second = Double.parseDouble(secondTF.getText());
sum = first + second;
product = first * second;
sumTF.setText("" + sum);
productTF.setText("" + product);
}
}
privateclass ExitButtonHandler implements ActionListener
{
publicvoid actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
publicstaticvoid main(String[] args)
{
SumProduct sumProductObject = new SumProduct();
}
}
11. a.
JLabel numOfCourses;
numOfCourses = new JLabel("Enter the number of courses");
b.
JButton run;
run = new JButton("Run");
c.
JTextField oneTextField ;
oneTextField = new JTextField(15);
d.
setTitle("Welcome Home!");
e.
setSize(200, 400);
f.
JTextField oneTextField;
oneTextField = new JTextField(15);
oneTextField.setText("Apple tree");
13. Lines with errors are in comments. See the corrected lines.
//The following lines added.
import javax.swing.*;
import java.awt.*;
publicclass RTwo extends JFrame
{
private JLabel length, width, area;
staticprivatefinalint WIDTH = 400;
staticprivatefinalint HEIGHT = 400;
//public RTwoProgram()
public RTwo()
{
//private JLabel length, width, area;
setTitle("Good day Area");
//length = JLabel("Enter the length);
length = new JLabel("Enter the length");
//width = JLabel("Enter the width);
width = new JLabel("Enter the width");
area = new JLabel("Area: ");
//containerPane = ContentPane();
Container pane = getContentPane();
//pane.setLayout(GridLayout(4, 1));
pane.setLayout(new GridLayout(4, 1));
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
publicstaticvoid main( String args[] )
{
//RTwoProgram R2 = new RTwoProgram ();
RTwo R2 = new RTwo();
}
}
15. displayWelcome, getAcctNo, getPin, verifyAcct, deposit, withdraw, transfer, tenderCash, checkAcct, and so on.
17. Customer: data members include firstName, lastName, phone, email, address; and methods include set and get methods for data members.
Account: accountNumber, type, currentRate; method includes set and get methods for data members.
Loan: loanNumber, type, currentRate; method includes set and get methods for data member
Manager: data members include firstName, lastName, phone, email, address; and methods include set and get methods for data members, createAccount, approveLoan, and so on.
Teller: data members include firstName, lastName, phone, email, address; and methods include set and get methods for data members, procesCheck, tenderCash, transferAmt and so on.
19. Company: data members include accountNumber, name, phone, email, address, status, numOpenings; and methods include set and get methods for data members, listOpenings, requestCandidate, cancelPosition, and so on.
Candidate: data members include candidateID, firstName, lastName, phone, email, address, wage and methods include set and get methods for data members, listQualifications, calculateSalary, withholdIncomeTax, and so on.
Placement: data members include candidateID, companyID, openingID, startDate, endDate; methods include set and get methods for data members, listQualifications, calculateSalary, informCompany, informCandiadate, and so on.
Opening: data members include openingID, companyID, startDate, endDate, qualificationID, salary; methods include set and get methods for data members.
Qualification: data members include qualificationID, meanSalary, maximumSalary, minimumSalary, categary; methods include set and get methods for data members.
Chapter 7
1.a. True; b. True; c. True; d. True; e. False; f. True; g. False; h. False;
3. a. 4b. 10.80c. 2.50d. 10.24e. 15.63
f. 5.00g. 2.50h. 9.00i. 28.00j. 36.00
5. a. The method main has no return type. It is a void method.
b. double
c. boolean
7.a. Invalid; Method type is missing.
b. Valid.
c. Invalid;Data type for the parameter b is missing.
d. Invalid; Missing parentheses after the method name.
9. The formal parameter x of the method signum is an integer. In the method call statement signum(20.5), a decimal value is used which is not an integer. So we could replace the expression signum(20.5) with the expression signum(20).
11. The method squareNum returns an int value while the expression x * x, in the return statement is a double value. One possible solution is to replace the expression x * x with the expression (int) x * x. Another solution is: In the method heading, change the method type from int to double.
13.a. 4; b. 26; c. 10 4 0; d. 0
15.a. 14; b. 15; c. 30
17. A void method can have a return statement. If a void method has a return statement, then it must be of the form return;, it should not return any value.
19.12
35
14
8
10
21.
1
2
6
24
120
23.
Method headings:
public static void main(String[] args)
public static void hello(int first, double second,
char ch)
Method bodies:
main: starts at Line 4 ends at Line 13
hello: starts at Line 16 ends at Line 20
Method definitions:
main: starts at Line 3 ends at Line 13
hello: starts at Line 14 ends at Line 20
Formal parameters:
main: args
hello: first, second, ch
Actual parameters:
x, y, z
x + 2, y - 3.5, 'S'
Method calls: Statements in Lines 9 and 11
hello(x, y, z); //Line 9
hello(x + 2, y - 3.5, 'S'); //Line 11
Local variables:
main: x, y, z
hello: num, y
25.
-14 20 126
15 40 407
15 80 1627
70 160 6412
27. a. Take Programming I.
b. TakeProgramming II.
c. TakeInvalid input. You must enter a 1 or 2
d. TakeInvalid input. You must enter a 1 or 2
29.
Identifier / Visibilityin traceMe / Visibilityin mainmain / Y / Y
local variables of main / N / Y
traceMe (function name) / Y / Y
x (traceMe’s formal parameter) / Y / N
y (traceMe’s formal parameter) / Y / N
z (traceMe’s local variable) / Y / N
31. public static void func(double x, double y)
{
if (x != 0)
System.out.println(y / x);
else
System.out.println("Because the first number is 0, "
+ "we cannot divide the second "
+ "number by the first number.");
}
Chapter 8
1. a. False; b. False; c. True; d. False; e. False;
3.Constructors have no type. Therefore the definition of the constructor with parameters should be:
publicAA(int a, int b)
{
x = a;
y = b;
}
5. a. (i) Constructor at Line 1.
(ii) Constructor at Line 3.
(iii) Constructor at Line 4.
b.
public CC()
{
u = 0;
v = 0;
w = 0.0;
}
c.
public CC(int a)
{
u = a;
v = 0;
w = 0.0;
}
d.
public CC(int a, int b)
{
u = a;
v = b;
w = 0.0;
}
e.
public CC(int a, int b, double d)
{
u = a;
v = b;
w = d;
}
7.Automobile
9. One.
11. a. It creates the object c1, and the instance variables hr, min, and sec are initialized to 0.
b. It creates the object c2.The instance variable hr is initialized to 5, the instance variable minis initialized to 12, andthe instance variable secis initialized to 30.
c. The values of the instance variables hr,min, and sec of theobject c1 are set to 3, 24, and 36, respectively.
d. The value of the instance variables hr of theobject c2is set to 9.
13. In Java, a class combines data and operations on data in a single unit. Typically, we do not want the user to directly manipulate the data, so data members are declared as private. To allow the users to manipulate the private members of a class, the user is provided public members. Therefore, we need bothpublicandprivate members in a class.
15. 06:23:17
06:23:17
17. In shallow copying, two or more reference variables of the same type point to the same object.
19. Both aa and bb point to the object bb.
21.The purpose of the copy constructor is to initialize an object, when the object is instantiated, using an existing object of the same type.
23. No.
25.publicclass Stock
{
private String name;
private doublepreviousPrice;
private doubleclosingPrice;
privateintnumberOfShares;
Stock()
{
name = "";
previousPrice = 0.0;
closingPrice = 0.0;
numberOfShares = 0;
}
Stock(String n, int prePr, int clPr, double shares)
{
name = n;
previousPrice = prePr;
closingPrice = clPr;
numberOfShares = shares;
}
public void setName(String n)
{
name = n;
}
public void setPreviousPrice(double p)
{
previousPrice = p;
}
public void setClosingPrice(double c)
{
closingPrice = c;
}
public void setNumberOfShare(int ns)
{
numberOfShares= ns;
}
public String getName()
{
returnname;
}
public int getPreviousPrice()
{
return previousPrice;
}
public double getClosingPrice()
{
return closingPrice;
}
public int getNumberOfShare()
{
return numberOfShares;
}
public doubleshareValues()
{
return numberOfShares * closingPrice;
}
public doublepercentGain()
{
return (previousPrice – closingPrice) / previousPrice * 100;
}
public String toString()
{
return ("Stock Name: " + name
+ "\r\n Previous Price: " + previousPrice
+ "\r\n Closing Price: " + closingPrice
+ "\r\n Number Of Shares: " + numberOfShares);
}
}
rogramming Exercises 6 and 7 with the following as indicated.
Chapter 9
1. a. True; b. True; c. True; d. True; e. False; f. False; g. True;