Chapter 4 Reference Answers
Questions
1. b 7. c 13. a
2. c 8. d 14. b
3. d 9. a 15. b
4. b 10. d 16. c
5. b 11. c 17. c
6. a 12. d 18. a
Exercises
1a.
// Password.java
// Chapter 4, Section A, Exercise 1a
public class Password {
public static void main (String[] args) throws Exception {
char p1, p2, p3, p4;
System.out.println("Please enter a " +
"four-character \npassword, and press Enter when done:");
p1 = (char)System.in.read();
p2 = (char)System.in.read();
p3 = (char)System.in.read();
p4 = (char)System.in.read();
System.out.println("Your password is: "
+ p1 + p2 + p3 + p4);
}
}
1b.
// Password2.java
// Chapter 4, Section A, Exercise 1b
public class Password2 {
public static void main (String[] args) throws Exception {
char p1, p2, p3, p4;
System.out.println("Please enter a four-character " +
"\npassword, and press Enter when done:");
p1 = (char)System.in.read();
p2 = (char)System.in.read();
p3 = (char)System.in.read();
p4 = (char)System.in.read();
System.out.println("Your password is: "
+ p1 + p2 + p3 + p4);
if (p1 == 'B')
System.out.println("Valid password");
else
System.out.println("Invalid password");
}
}
1c.
// Password3.java
// Chapter 4, Section A, Exercise 1c
public class Password3 {
public static void main (String[] args) throws Exception {
char p1, p2, p3, p4;
boolean passTest = true;
System.out.println("Please enter a four-character " +
"\npassword, and press Enter when done:");
p1 = (char)System.in.read();
p2 = (char)System.in.read();
p3 = (char)System.in.read();
p4 = (char)System.in.read();
System.out.println("Your password is: "
+ p1 + p2 + p3 + p4);
if (p1 != 'B')
passTest = false;
if (p2 != 'O')
passTest = false;
if (p3 != 'L')
passTest = false;
if (p4 != 'T')
passTest = false;
if (passTest == true)
System.out.println("Valid password");
else
System.out.println("Invalid password");
}
}
2a.
// Furniture.java
// Chapter 4, Section A, Exercise 2a
public class Furniture {
public static void main (String[] args) throws Exception {
char selection;
System.out.println("\tMenu\n\n\tPine (P)\n\tOak (O)\n\tMahogany (M)");
System.out.print("\n\n\tEnter Selection (P, O, M): ");
selection = (char)System.in.read();
if (selection == 'P')
System.out.println("\nPine table cost is $100");
else if (selection == 'O')
System.out.println("\nOak table cost is $225");
else if (selection == 'M')
System.out.println("\nMahogany table cost is $310");
else
System.out.println("\nInvalid Selection...");
}
}
2b.
// FurnitureSizes.java
// Chapter 4, Section A, Exercise 2b
public class FurnitureSizes {
public static void main (String[] args) throws Exception {
char selection;
char size;
System.out.println("\tMenu\n\n\tPine (P)\n\tOak (O)\n\tMahogany (M)");
System.out.print("\n\n\tEnter Selection (P, O, M): ");
selection = (char)System.in.read();
// discard the Enter key
System.in.read();
System.in.read();
System.out.print("\n\nEnter Size, Large (L), Small (S): ");
size = (char)System.in.read();
// check type and size, use small for size for default
if (selection == 'P') {
System.out.print("\nPine table cost is ");
if (size == 'L')
System.out.println("$135");
else
System.out.println("$100");
}
if (selection == 'O') {
System.out.print("\nOak table cost is ");
if (size == 'L')
System.out.println("$260");
else
System.out.println("$225");
}
if (selection == 'M') {
System.out.print("\nMahogany table cost is ");
if (size == 'L')
System.out.println("$345");
else
System.out.println("$310");
}
else
System.out.println("\nInvalid Selection...");
}
}
3.
// Admission.java
// Chapter 4, Section A, Exercise 3
public class Admission {
public static void main (String[] args) throws Exception {
double gpa = 3.5;
int score = 59;
System.out.println("The Grade Point Average is " + gpa);
System.out.println("The Score is " + score);
if ((score >= 80) || (gpa >= 3.0 && score >= 60))
System.out.println("Accept");
else
System.out.println("Reject");
}
}
4.
// Payroll.java
// Chapter 4, Section A, Exercise 4
public class Payroll {
public static void main (String[] args) throws Exception {
double hourlyRate = 25;
double hoursWorked = 40;
double withholdingTax;
double pctTax;
double grossPay = hourlyRate * hoursWorked;
if (grossPay > 300.00)
pctTax = .12;
else
pctTax = .10;
withholdingTax = grossPay * pctTax;
System.out.println("The gross pay for "
+ hoursWorked + " hours worked"
+ " at a rate of " + hourlyRate + " per hour is "
+ grossPay + "\nThe net pay is "
+ (grossPay - withholdingTax)
+ " based on tax rate of " + pctTax);
}
}
5a.
// Calculate.java
// Chapter 4, Section A, Exercise 5a
public class Calculate {
public static void main (String[] args) throws Exception {
char selection;
int number1 = 18;
int number2 = 5;
System.out.print("Enter A(dd), S(ubtract), M(ultiply): ");
selection = (char)System.in.read();
if (selection == 'A')
System.out.println(number1 + " plus "
+ number2 + " = " + (number1 + number2));
else if (selection == 'S')
System.out.println(number1 + " minus "
+ number2 + " = " + (number1 - number2));
else if (selection == 'M')
System.out.println(number1 + " times "
+ number2 + " = " + (number1 * number2));
else
System.out.println("\nInvalid Selection...");
}
}
5b.
// Calculate2.java
// Chapter 4, Section A, Exercise 5b
public class Calculate2 {
public static void main (String[] args) throws Exception {
char selection;
int number1 = 18;
int number2 = 0;
System.out.print("Enter A(dd), S(ubtract), M(ultiply), D(ivide): ");
selection = (char)System.in.read();
if (selection == 'A')
System.out.println(number1 + " plus "
+ number2 + " = " + (number1 + number2));
else if (selection == 'S')
System.out.println(number1 + " minus "
+ number2 + " = " + (number1 - number2));
else if (selection == 'M')
System.out.println(number1 + " times "
+ number2 + " = " + (number1 * number2));
else if (selection == 'D')
if (number2 == 0)
System.out.println("Divide by zero error...");
else
System.out.println(number1 + " divided by "
+ number2 + " = " + (number1 / number2));
else
System.out.println("\nInvalid Selection...");
}
}
6a.
// Lawn.java
// Chapter 4, Section A, Exercise 6a
public class Lawn {
public static void main (String[] args) throws Exception {
int length = 10, width = 54;
int lotSize = length * width;
int weeklyFee;
if (lotSize < 400)
weeklyFee = 25;
else if (lotSize < 600)
weeklyFee = 35;
else
weeklyFee = 50;
System.out.println("The your payment for a lot of "
+ lotSize + " square feet is "
+ weeklyFee + " per week or "
+ (weeklyFee * 20) + " seasonal fee");
}
}
6b.
// Lawn2.java
// Chapter 4, Section A, Exercise 6b
public class Lawn2 {
public static void main (String[] args) throws Exception {
int length = 10, width = 54;
int lotSize = length * width;
int weeklyFee;
char selection;
if (lotSize < 400)
weeklyFee = 25;
else if (lotSize < 600)
weeklyFee = 35;
else
weeklyFee = 50;
System.out.println("\tMenu\n\n\tOne Payment (A)" +
"\n\tTwo Payments (B)\n\tWeekly(C)");
System.out.print("\n\n\tEnter Selection (A, B, C): ");
selection = (char)System.in.read();
System.out.print("Your payment for a lot of "
+ lotSize + " square feet is ");
if (selection == 'A')
System.out.print("\none payment of " + weeklyFee * 20);
else if (selection == 'B')
System.out.print("\ntwo payments of " + ((weeklyFee * 20) / 2 + 5) );
else if (selection == 'C')
System.out.print("\ntwenty weekly payments of " + (weeklyFee + 3));
else
System.out.print("\nnot available due to an invalid payment selection...");
}
}
7a.
// Balance.java
// Chapter 4, Section A, Exercise 7a
public class Balance {
public static void main (String[] args) throws Exception {
double checkingBalance = 1500.50;
double savingsBalance = 1500.70;
if (checkingBalance > savingsBalance)
System.out.println("Checking is higher");
else
System.out.println("Checking is not higher");
}
}
7b.
// Balance2.java
// Chapter 4, Section A, Exercise 7b
public class Balance2 {
public static void main (String[] args) throws Exception {
double checkingBalance = 1500.50;
double savingsBalance = 0;
if ((checkingBalance < 0) && (savingsBalance < 0))
System.out.println("Both accounts in the red");
else if ((checkingBalance < savingsBalance)
&& (checkingBalance >= 0))
System.out.println("Both accounts are in the black");
}
}
8.
// Employee.java
// Chapter 4, Section A, Exercise 8
public class Employee {
private static int COMPANY_ID = 12345;
private int empNum;
private double empSalary;
Employee( ) throws Exception {
System.out.print("Enter 3-digit employee number: ");
// temp chars to accept bytes from input stream
char a1, a2, a3;
// temp numbers used in converting the chars
int n1, n2, n3;
// a dummy variable to throw away the Enter key
int ta;
a1 = (char)System.in.read(); // read first digit
a2 = (char)System.in.read(); // read second digit
a3 = (char)System.in.read(); // read third digit
ta = System.in.read(); // get rid of newline char
ta = System.in.read(); // get rid of newline char
n1 = Character.digit(a1, 10); // convert to a number
n2 = Character.digit(a2, 10); // convert to a number
n3 = Character.digit(a3, 10); // convert to a number
// put the number back together
empNum = (n1*100) + (n2*10) + n3;
System.out.println("empNum is " + empNum);
}
public void showCompanyID() {
System.out.println("Worker " + empNum
+ " has company ID " + COMPANY_ID);
}
}
Chapter 4 - Section B
Questions
1. d 7. b 13. c
2. c 8. c 14. b
3. a 9. b 15. d
4. d 10. d 16. c
5. d 11. c 17. c
6. a 12. b 18. c
19. c
Exercises
1.
// PickEmployee.java
// Chapter 4, Section B, Exercise 1
public class PickEmployee {
public static void main (String[] args) throws Exception {
char selection;
System.out.print("Enter an initial (A, B or Z): ");
selection = (char)System.in.read();
switch(selection) {
case 'A':
System.out.println("Armando");
break;
case 'B':
System.out.println("Bruno");
break;
case 'Z':
System.out.println("Zachary");
break;
default:
System.out.println("No such employee");
}
}
}
2.
// GetVowel.java
// Chapter 4, Section B, Exercise 2
public class GetVowel {
public static void main (String[] args) throws Exception {
char selection;
System.out.print("Enter a vowel: ");
selection = (char)System.in.read();
switch(selection) {
case 'a':
case 'A':
System.out.println(selection + " is a vowel");
break;
case 'e':
case 'E':
System.out.println(selection + " is a vowel");
break;
case 'i':
case 'I':
System.out.println(selection + " is a vowel");
break;
case 'o':
case 'O':
System.out.println(selection + " is a vowel");
break;
case 'u':
case 'U':
System.out.println(selection + " is a vowel");
break;
default:
System.out.println(selection + " is NOT a vowel");
}
}
}
3.
// IQ.java
// Chapter 4, Section B, Exercise 3
public class IQ {
public static void main (String[] args) throws Exception {
int iqScore = 285;
if (iqScore < 0 || iqScore > 200)
System.out.println(iqScore + " is an invalid IQ score");
else if (iqScore == 100)
System.out.println(iqScore + " is average");
else if (iqScore < 100)
System.out.println(iqScore + " is below average");
else
System.out.println(iqScore + " is above average");
}
}
4.
// Admissions2.java
// Chapter 4, Section B, Exercise 4
public class Admissions2 {
public static void main (String[] args) throws Exception {
double gpa = 3.5;
int score = 59;
System.out.println("The Grade Point Average is " + gpa);
System.out.println("The Score is " + score);
if (gpa >= 3.6 && score >= 60)
System.out.println("Accept");
else if (gpa >= 3.0 && score >= 70)
System.out.println("Accept");
else if (gpa >= 2.6 && score >= 80)
System.out.println("Accept");
else if (gpa >= 2.0 && score >= 90)
System.out.println("Accept");
else
System.out.println("Reject");
}
}
5.
// Payroll2.java
// Chapter 4, Section A, Exercise 5
public class Payroll2 {
public static void main (String[] args) throws Exception {
double hourlyRate = 25;
double hoursWorked = 40;
double withholdingTax;
double pctTax = 0.0;
double grossPay = hourlyRate * hoursWorked;
if (grossPay <= 300.00)
pctTax = .10;
else if (grossPay >= 300.01 && grossPay <= 400.00)
pctTax = .12;
else if (grossPay >= 400.01 && grossPay <= 500.00)
pctTax = .15;
else if (grossPay >= 500.01)
pctTax = .20;
withholdingTax = grossPay * pctTax;
System.out.println("The gross pay for "
+ hoursWorked + " hours worked"
+ " at a rate of " + hourlyRate + " per hour is "
+ grossPay + "\nThe net pay is "
+ (grossPay - withholdingTax)
+ " based on tax rate of " + pctTax);
}
}
6.
// PetAdvice.java
// Chapter 4, Section B, Exercise 6
public class PetAdvice {
public static void main (String[] args) throws Exception {
char abode, hours;
System.out.print("Enter A (apartment), H (house), D (dormitory): ");
abode = (char)System.in.read();
System.in.read();
System.in.read();
System.out.println("How many hours do you spend at home per day? ");
System.out.print("Enter A (18 or more), B (10 to 17), "
+ "D (6 to 7) or E (0 - 5): ");
hours = (char)System.in.read();
System.in.read();
System.in.read();
System.out.print("Your pet recommendation is ");
if ((abode == 'H') && (hours == 'A'))
System.out.println("Pot bellied pig");
else if ((abode == 'H') && (hours == 'B'))
System.out.println("Dog");
else if ((abode == 'H') && (hours == 'D' || hours == 'E'))
System.out.println("Snake");
else if ((abode == 'A') && (hours == 'A' || hours == 'B'))
System.out.println("Cat");
else if ((abode == 'A') && (hours == 'D' || hours == 'E' || hours == 'C'))
System.out.println("Hamster");
else if ((abode == 'D') && (hours != 'E'))
System.out.println("Fish");
else if ((abode == 'D') && (hours == 'E'))
System.out.println("Ant Farm");
else
System.out.println("not able to be determined");
}
}
7.
// Siblings.java
// Chapter 4, Section B, Exercise 7
public class Siblings {
public static void main (String[] args) {
int myNumberOfSiblings = 3;
int yourNumberOfSiblings = 5;
if (myNumberOfSiblings > yourNumberOfSiblings)
System.out.println("I have " + myNumberOfSiblings
+ " siblings and you have " + yourNumberOfSiblings
+ "\nI have more siblings ");
else if (myNumberOfSiblings < yourNumberOfSiblings)
System.out.println("I have " + myNumberOfSiblings
+ " siblings and you have " + yourNumberOfSiblings
+ "\nYou have more siblings ");
else
System.out.println("We have the same number of siblings: " +
myNumberOfSiblings );
}
}
8.
// Credits.java
// Chapter 4, Section B, Exercise 8
public class Credits {
public static void main (String[] args) {
int myNumberOfCredits = 124;
int yourNumberOfCredits = 50;
if (myNumberOfCredits > yourNumberOfCredits)
System.out.println("I have " + myNumberOfCredits
+ " Credits and you have " + yourNumberOfCredits
+ "\nI have more Credits ");
else if (myNumberOfCredits < yourNumberOfCredits)
System.out.println("I have " + myNumberOfCredits
+ " Credits and you have " + yourNumberOfCredits
+ "\nYou have more Credits ");
else
System.out.println("We have the same number of Credits: "
+ myNumberOfCredits );
}
}
9.
// Store.java
// Chapter 4, Section B, Exercise 9
public class Store {
public static void main (String[] args) throws Exception {
char sel1 = 'x', sel2 = 'x', yesNo = 'x';
double cost = 0.0;
System.out.println("\tMenu\n\n\tHammer, 5.99 (a)\n\tSaw, 11.99 (b)"
+ "\n\tShovel, 25.99 (c)");
System.out.print("\n\n\tEnter Selection (a, b, c): ");
sel1 = (char)System.in.read();
System.in.read();
System.in.read();
System.out.print("\n\nSelect another product (y or n): ");
yesNo = (char)System.in.read();
System.in.read();
System.in.read();
if (yesNo == 'y') {
System.out.println("\tMenu\n\n\tHammer, 5.99 (a)\n\tSaw, 11.99 (b)" +
"\n\tShovel, 25.99 (c)");
System.out.print("\n\n\tEnter Selection (a, b, c): ");
sel2 = (char)System.in.read();
System.in.read();
System.in.read();
}
switch(sel1) {
case 'a':
cost = 5.99;
break;
case 'b':
cost = 11.99;
break;
case 'c':
cost = 25.99;
}
switch(sel2) {
case 'a':
cost = cost + 5.99;
break;
case 'b':
cost = cost + 11.99;
break;
case 'c':
cost = cost + 25.99;
}
System.out.println("\nThe cost of your item is: " + cost);
}
}
Chapter 4 - Section C
Questions
1. b 8. b 15. d
2. b 9. a 16. b
3. a 10. c 17. b
4. d 11. c 18. b
5. b 12. d 19. a
6. a 13. a 20. a
7. b 14. b
Exercises
1.
// EvenNums.java
// Chapter 4, Section C, Exercise 1
public class EvenNums {
public static void main (String[] args) throws Exception {
for (int i = 2; i <= 100; i++)
if ((i % 2) == 0)
System.out.println(i);
}
}
2.
// ABCInput.java
// Chapter 4, Section C, Exercise 2
public class ABCInput {
public static void main (String[] args) throws Exception {
char selection = 'x';
while (selection != 'Q') {
System.out.print("Enter Selection (A, B, C, Q): ");
selection = (char)System.in.read();
System.in.read();
System.in.read();
switch(selection) {
case 'Q':
break;
case 'A':
case 'B':
case 'C':
System.out.println("Good Job!");
break;
default:
System.out.println("Invalid selection");
}
}
}
}
3.
// TableOfSquares.java
// Chapter 4, Section C, Exercise 3
public class TableOfSquares {
public static void main (String[] args) {
for (int i = 1; i <= 20; i++)
System.out.println("Integer " + i +
" squared is " + i * i);
}
}
4.
// Sum50.java
// Chapter 4, Section C, Exercise 4
public class Sum50 {
public static void main (String[] args) throws Exception {
int total = 0;
for (int i = 1; i <= 50; i++)
total += i;
System.out.println("The total of the integers from 1 to 50 is " + total);
}
}
5.
// EverySum.java
// Chapter 4, Section C, Exercise 5
public class EverySum {
public static void main (String[] args) {
int sum = 0;
for (int i = 1; i <= 50; i++) {
sum += i;
System.out.print(" " + sum);
}
}
}
6.
// Perfect.java
// Chapter 4, Section C, Exercise 6
public class Perfect {
public static void main (String[] args){
for (int i = 2; i <= 1000; i++) {
if (perfect(i) == true)
System.out.println("The number " + i
+ " is perfect");
}
}
public static boolean perfect(int n){
int sum = 1;
for (int j = 2; j <= n/2; j++)
if (n % j == 0)
sum += j;
if (sum == n)
return true;
return false;
}
}
7.
// Investment.java
// Chapter 4, Section C, Exercise 7
public class Investment {
public static void main (String[] args) throws Exception {
double investment;
int term;
char selection;
System.out.println("Select Investment Amount");
System.out.print("Enter a (200,000), b (100,000), c (50,000): ");
selection = (char)System.in.read();
System.in.read();
System.in.read();
switch(selection) {
case 'a':
investment = 200000.00;
break;
case 'b':
investment = 100000.00;
break;
case 'c':
investment = 50000.00;
break;
default:
investment = 0.0;
}
System.out.println("Select Number of Years");
System.out.print("Enter a (30), b (20), c (15): ");
selection = (char)System.in.read();
System.in.read();
System.in.read();
switch(selection) {
case 'a':
term = 30;
break;
case 'b':
term = 20;
break;
case 'c':
term = 15;
break;
default:
term = 0;
}
if (term == 0 || investment == 0) {
System.out.println("Not enough information");
return;
}
System.out.println("Your Investment:");
for (int i = 1; i <= term; i++) {
System.out.println("Year " + i
+ " amount at 12% is "
+ (investment * (Math.pow((1 + .12),i))));
}
}
}
8.
// Quiz.java
// Chapter 4, Section C, Exercise 8
public class Quiz {
public static void main (String[] args) throws Exception {
String javaQuestion = new String("Is Java better than C++ (enter y or n):");
String cQuestion = new String("Is C++ better than Java (enter y or n):");
String question;
char selection, answer;
int numCorrect = 0;
System.out.println("Select Quiz");
System.out.print("Enter a (C++), b (Java), c (EXIT): ");
selection = (char)System.in.read();
System.in.read();
System.in.read();
switch(selection) {
case 'a':
question = cQuestion;
answer = 'n';
break;
case 'b':
question = javaQuestion;
answer = 'y';
break;
default:
return;
}
System.out.print(question);
char response = (char)System.in.read();
System.in.read();
System.in.read();
if (response == answer) {
System.out.println("Correct!");
numCorrect++;
}
else
System.out.println("Incorrect!" +
"\nCorrect answer is " + answer);
System.out.println("Number of correct answers: " + numCorrect);
}
}
9.
// Survey.java
// Chapter 4, Section C, Exercise 9
public class Survey {
public static void main (String[] args) throws Exception {
String ques1 = new String("Is Java better than C++? ");
String ques2 = new String("Is C++ better than Java? ");
String ques3 = new String("Is C better than Java? ");
String ques4 = new String("Is Pascal better than Java? ");
String question;
char selection, answer, response;
char another = 'y';
int i;
while (another == 'y') {
int numCorrect = 0;
for (i = 1; i <= 4; i++) {
if (i == 1) {
question = ques1;
answer = 'y';
}
else if (i == 2) {
question = ques2;
answer = 'n';
}
else if (i == 3) {
question = ques3;
answer = 'n';
}
else {
question = ques4;
answer = 'n';
}
System.out.println("Enter y or n for the following questions");
System.out.print(question);
response = (char)System.in.read();
System.in.read();
System.in.read();
if (response == answer) {
System.out.println("Correct!");
numCorrect++;
}
else
System.out.println("Incorrect!" +
"\nCorrect answer is " + answer);
}
System.out.println("\nNumber of correct answers: " + numCorrect);
System.out.print("\nEnter another set of responses (y or n):");
another = (char)System.in.read();
System.in.read();
System.in.read();
}
}
}
10a.
public class FixDebugFour01
// Adds your bill for burger and fries {
public static void main(String[] args) throws Exception {
char usersChoice;
double bill = 0.0;
System.out.println("Do you want a burger?");
System.out.println("Enter y or n.");
usersChoice= (char)System.in.read();
System.in.read();
System.in.read();
if(usersChoice == 'y')
bill +=2.59;
System.out.println("Fries with that?");
usersChoice = (char)System.in.read();
if (usersChoice == 'y')
bill+=.89;
System.out.println("Bill is " + bill);
}
}
10b.
public class FixDebugFour02{
// prints odd numbers
// prints new line after every 10
public static void main(String[] args) {
int num, count = 0;
for(num = 1; num <= 100; num+=2){
System.out.print(" " + num);
++count;
if(count == 10) {
count = 0;
System.out.println();
}
}
System.out.println("End of odd numbers");
}
}
10c.
public class FixDebugFour03{
// start with a penny
// double it every day
// how much do you have in a month?
public static void main(String[] args) {
double money = .01;
int day=1;
while(day < 30) {
money = 2 * money;
++day;
System.out.println("After day " + day +
" you have " + money);
}
}
}
10d.
public class FixDebugFour04 {
public static void main(String[] args) {
char letter;
int a = 0;
for(a = 65; a <= 122; a++) {
letter = (char)a;
System.out.print(" " + letter);
if((a==85)||(a == 105))
System.out.println();
}
System.out.println("\nEnd of program");
}
}