(Updated August 26, 2020)
Table of contents
-
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7a
Chapter 7b
Chapter 8
Chapter 9
Chapter 9s
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15a
Chapter 15b
Chapter 16
Chapter 17
Chapter 18
Chapter 1
[Note: There are no specific answers to Chapter 1.]Chapter 2
Exercise 1 solution
String name;
Exercise 2 solution
int i;
double d;
boolean b;
Exercise 3 solution
i = 35;
d = 3.14;
b = false;
System.out.println("i is " + i);
System.out.println("d is " + d);
System.out.println("b is " + b);
Alternative println
with newlines
System.out.println("i is " + i + "\nd is " + d + "\nb is " + b);
Exercise 5 solution
Scanner kb = new Scanner(System.in);
System.out.print("Enter an integer: ");
i = kb.nextInt();
System.out.print("Enter a double: ");
d = kb.nextDouble();
System.out.print("Enter a boolean: ");
i = kb.nextBoolean();
Chapter 3
- (Beginner) Which package would you find the following classes:
java.util
java.io
java.lang
java.io
javax.swing
java.lang
java.lang
java.lang
- (Beginner) Which class would you find the following methods:
Math
String
String
Scanner
Math
JOptionPane
String
Scanner
String
PrintWriter
PrintWriter
- (Intermediate) In your IDE, create some method calls as practice using:
input = showInputDialog("Enter your name:");
showMessageDialog(null, "Thank you!");
choice = JOptionPane.showConfirmDialog(null, "Confirm quit?");
- (Intermediate) Write statements using
Math.random()
for the following ranges:(int)(Math.random() * 5 + 2);
(int)(Math.random() * 7 + 3);
(int)(Math.random() * 26 + 30);
(int)(Math.random() * 7 +59);
- (Intermediate) Using the
indexOf()
String
method, write statements to split the following strings into two parts:-
int p; String part1, part2, s = "Sally Mathers"; p = s.indexOf(" "); part1 = s.substring(0,p); part2 = s.substring(p+1);
-
int p; String part1, part2, s = "3d6"; p = s.indexOf("d"); part1 = s.substring(0,p); part2 = s.substring(p+1);
-
int p; String part1, part2, s = "44*36"; p = s.indexOf("*"); part1 = s.substring(0,p); part2 = s.substring(p+1);
-
Chapter 4
Exercise 1 solution
public class Ch4Ex1 {
public static void main(String[] args) {
// DC is 16, constitution modifier is 2.
int dc = 16, roll, conmod = 2;
roll = (int)(Math.random() * 20 + 1);
System.out.println("DC = " + dc + ", roll = " + roll + ", mod = " + conmod);
if ( roll + conmod >= dc )
System.out.println("A sense of nausea comes over you and then immediately dissipates.");
else {
System.out.println("You feel very sick and extremely pain in your muscles.");
System.out.println("You are now considered poisoned.");
}
}
}
Exercise 2 solution
public class Ch4Ex2 {
public static void main(String[] args) {
String sdow = "Tuesday";
String ndow;
switch ( sdow ) {
case "Sunday" :
ndow = 0;
break;
case "Monday" :
ndow = 1;
break;
case "Tuesay" :
ndow = 2;
break;
case "Wednesday" :
ndow = 3;
break;
case "Thursday" :
ndow = 4;
break;
case "Friday" :
ndow = 5;
break;
case "Saturday" :
ndow = 6;
break;
}
}
}
Exercise 3 solution
public class Ch4Ex3 {
public static void main(String[] args) {
char letterGrade = 'A';
int qp;
/* Original code
switch (letterGrade)
{
case 'a': case 'A':
qp = 4; break;
case 'b': case 'B':
qp = 3; break;
case 'c': case 'C':
qp = 2; break;
case 'd': case 'D':
qp = 1; break;
default:
qp = 0; break;
}
*/
if ( letterGrade == 'A' || letterGrade == 'a' )
qp = 4;
else if ( letterGrade == 'B' || letterGrade =='b' )
qp = 3;
else if ( letterGrade == 'C' || letterGrade =='c' )
qp = 2;
else if ( letterGrade == 'D' || letterGrade == 'd' )
qp = 1;
else
qp = 0;
}
}
Exercise 4 solution
import java.util.Scanner;
public class Ch4Ex4 {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
String s1, s2;
System.out.print("Enter a string: ");
s1 = kb.nextLine();
System.out.print("Enter another string: ");
s2 = kb.nextLine();
System.out.println("The strings are: \n" + s1 + "\n" + s2 + "\n");
if (s1.compareTo(s2) > 0)
System.out.println("\"" + s1 + "\" is the greater string.");
else
System.out.println("\"" + s2 + "\" is the greater string.");
}
}
Exercise 5 solution
import java.util.Scanner;
public class Ch4Ex5 {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
String s1, s2;
System.out.print("Enter a string: ");
s1 = kb.nextLine();
System.out.print("Enter another string: ");
s2 = kb.nextLine();
System.out.println("The strings are: \n" + s1 + "\n" + s2 + "\n");
System.out.println("\"" + (s1.compareTo(s2) > 0 ? s1 : s2) + "\" is the greater string.");
}
}
Chapter 5
Exercise 1 solution
import java.util.Scanner;
public class Ch5Ex1 {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
int sum = 0;
int x=0, value;
double avg;
System.out.print("Enter value #" + (x+1) + " (CTRL-D to end): ");
while ( kb.hasNext() )
{
value = kb.nextInt();
sum = sum + value;
x++;
System.out.print("Enter value #" + (x+1) + " (CTRL-D to end): ");
}
// avoid divide by zero.
if ( x > 0 ) {
avg = sum / (double)x;
System.out.println("The sum is " + sum + ".");
System.out.println("The average is " + avg + ".");
}
}
}
Exercise 2 solution
import java.util.Scanner;
public class Ch5Ex2 {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
char grade;
int x, qp, qpTotal=0;
double gpa;
System.out.println("Enter 4 grades and receive the GPA.");
System.out.println("Each course is considered 4 credits.\n");
for ( x = 1; x < 5; x++ ) {
System.out.print("Enter grade #" + x + ": ");
grade = kb.next().charAt(0);
switch (grade)
{
case 'a': case 'A':
qp = 4; break;
case 'b': case 'B':
qp = 3; break;
case 'c': case 'C':
qp = 2; break;
case 'd': case 'D':
qp = 1; break;
default:
qp = 0; break;
}
qpTotal = qpTotal + qp * 4;
}
gpa = qpTotal / 16.0;
System.out.printf("The GPA is %.2f%n", gpa);
}
}
Exercise 3 solution
import java.util.Scanner;
public class Ch5Ex3 {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
char grade;
int x, qp, qpTotal=0, credits, creditTotal=0;
double gpa;
System.out.println("Enter 4 grades and the credits for each course");
System.out.println("You will then receive the GPA.\n");
for ( x = 1; x < 5; x++ ) {
System.out.print("Enter grade #" + x + ": ");
grade = kb.next().charAt(0);
System.out.print("Enter credits for grade #" + x + ": ");
credits = kb.nextInt();
switch (grade)
{
case 'a': case 'A':
qp = 4; break;
case 'b': case 'B':
qp = 3; break;
case 'c': case 'C':
qp = 2; break;
case 'd': case 'D':
qp = 1; break;
default:
qp = 0; break;
}
creditTotal = creditTotal + credits;
qpTotal = qpTotal + qp * credits;
}
gpa = qpTotal / (double)creditTotal;
System.out.printf("The GPA is %.2f%n", gpa);
}
}
Exercise 4 solution
import java.util.Scanner;
public class Ch5Ex4 {
static Scanner kb = new Scanner(System.in);
public static void main(String[] args) {
String line;
int x, count;
System.out.print("Enter a string (CTRL-D to end): ");
while ( kb.hasNext() )
{
line = kb.nextLine();
count = 0;
for ( x = 0; x < line.length(); x++ ) {
char ch = line.charAt(x);
if ( Character.isLetter(ch) )
count++;
}
System.out.println("There are " + count + " letters.");
count = 0;
for ( x = 0; x < line.length(); x++ ) {
char ch = line.charAt(x);
if ( Character.isWhitespace(ch) )
count++;
}
System.out.println("There are " + count + " whitespace.\n");
System.out.print("Enter a string (CTRL-D to end): ");
}
}
}
Chapter 6
Exercise 1 - 3 solutions
public class Ch6Ex1_3 {
/* This piece of code defines and tests the methods from the first
three exercises of Charpter 6.
*/
// Exercise 1
public static int sum (int a, int b) {
return a + b;
}
// Exercise 2
public static String concat (String a, String b) {
return a + b;
}
// Exercise 3
public static short sum (short a, short b) {
/* although the parameters are shorts, the return
is still treated as an int.
*/
return (short)(a + b);
}
public static long sum (long a, long b) {
return a + b;
}
public static void main(String[] args) {
String st1="ABDC", st2="1234";
int i1=10, i2=15;
short s1=20, s2=30;
long l1=50, l2=60;
System.out.println("sum using ints = " + sum(i1, i2));
System.out.println("concat of two strings = " + concat(st1, st2));
System.out.println("sum using shorts = " + sum(s1, s2));
System.out.println("sum using longs = " + sum(l1, l2));
}
}
Exercise 4 - 5 solutions
public class Ch6Ex4_5 {
// Exercise 4
public static int indexOf(String s, char c) {
int x, l;
l = s.length();
for ( x = 0; x < l; x++)
if (s.charAt(x) == c)
return x;
return -1;
}
// Exercise 5
public static int rindexOf(String s, char c) {
int x, l;
l = s.length();
for ( x = l-1; x >= 0; x--)
if (s.charAt(x) == c)
return x;
return -1;
}
public static void main(String[] args) {
String t = "The quick brown fox jumps over the lazy dog.";
System.out.println("First forward occurrence of 'o' in t is " + indexOf(t, 'o'));
System.out.println("First forward occurrence of '?' in t is " + indexOf(t, '?'));
System.out.println("First reverse occurrence of 'o' in t is " + rindexOf(t, 'o'));
System.out.println("First reverse occurrence of '?' in t is " + rindexOf(t, '?'));
}
}
Exercise 6 solution
public class Ch6Ex6 {
/* This solution shows a great opportunity
for the ternary operator ?:. The if/else
version is commented out.
*/
public static String replace(String s, char o, char n) {
String r = "";
int x, l = s.length();
for ( x = 0; x < l; x++ ) {
char c = s.charAt(x);
/*
if ( c == o )
r = r + n;
else
r = r + c;
*/
r += ( c == o ) ? n : c;
}
return r;
}
public static void main(String[] args) {
System.out.println(replace("Mississippi", 's', 'z'));
}
}
Exercise 7 solution
public class Ch6Ex7 {
/*
Base conversions are actually quite easy once you devise
multiplying before you add. The other part is that we are
converting from String to int.
For a char, if it is in the proper range, we can subtract
'0' from it. So '9' - '0' = 9, '0' - '0' = 0, etc.
*/
public static int parseInt(String s) {
int x, l = s.length(), sum = 0;
for ( x = 0; x < l; x++) {
char c = s.charAt(x);
if ( c >= '0' && c <= '9' )
sum = sum * 10 + c - '0';
else
// Exceptions are discussed in Chapter 12.
throw new NumberFormatException("Illegal digit '" + c + "'.");
}
return sum;
}
public static int parseInt(String s, int r) {
int x, l = s.length(), sum = 0, d;
// We can handle up to base 36. Position is digit value.
String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Upcase the string to make things easier.
s = s.toUpperCase();
for ( x = 0; x < l; x++) {
char c = s.charAt(x);
// Get digit value from string or -1 and check range.
d = digits.indexOf(c);
if ( d >= 0 && d < r )
sum = sum * r + d;
else
// Exceptions are discussed in Chapter 12.
throw new NumberFormatException("Illegal digit '" + c + "'.");
}
return sum;
}
public static void main(String[] args) {
System.out.println("parseInt(\"4096\") = " + parseInt("4096"));
//System.out.println("parseInt(\"409A\") = " + parseInt("409A"));
System.out.println("parseInt(\"1101001\", 2) = " + parseInt("1101001", 2));
//System.out.println("parseInt(\"1101002\", 2) = " + parseInt("1101002", 2));
System.out.println("parseInt(\"177\", 8) = " + parseInt("177", 8));
//System.out.println("parseInt(\"178\", 8) = " + parseInt("178", 8));
System.out.println("parseInt(\"4096\", 10) = " + parseInt("4096", 10));
//System.out.println("parseInt(\"409A\", 10) = " + parseInt("409A", 10));
System.out.println("parseInt(\"FaCe\", 16) = " + parseInt("FaCe", 16));
System.out.println("parseInt(\"FaC;\", 16) = " + parseInt("FaC;", 16));
}
}
Chapter 7a
Chapter 7b
Chapter 8
Chapter 9
Exercise 1 solution
public class Ch9Ex1 {
public static void main(String[] args) {
int ia[] = new int[25];
// populate with random numbers.
for (int x = 0; x < ia.length; x++) {
ia[x] = (int)(Math.random() * 100);
}
// print 5x5 grid
for (int x = 0; x< ia.length; x++) {
System.out.printf("%4d", ia[x]);
if ( (x+1) % 5 == 0)
System.out.println();
}
}
}
Chapter 9s
Exercise 2 solution
import java.util.Arrays;
import java.util.Vector;
public class Ch9sEx2 {
public static void main(String[] args) {
int median, x, a[] = {4,5,7,8,4,3,2,8,7,4,5,7,8,9,0,1,2,6,7,8,4};
int cur, ccount, mcount = 0;
Vector mode = new Vector();
Arrays.sort(a);
System.out.println(Arrays.toString(a));
int l = a.length;
// NOTE: This code does NOT handle bi-modal or multi-modal data!
cur = a[0];
ccount = 1;
for ( x = 0; x < l; x++ ) {
System.out.println(cur + " " + a[x]);
if ( cur == a[x] ) {
ccount++;
} else {
System.out.println(cur + " appeared " + ccount + " times.");
// set the new mode?
if ( ccount == mcount)
mode.add(cur);
if ( ccount > mcount ) {
//mode = new Vector();
mode.removeAllElements();
mode.add(cur);
mcount = ccount;
}
// Always!
ccount = 1;
cur = a[x];
}
}
System.out.println("The mode is " + mode);
}
}
Exercise 2 solution
public class Ch9Ex2 {
public static void dumpArray (int[] array) {
int x, l = array.length;
System.out.print("[ ");
for ( x = 0 ; x < l - 1 ; x++ )
System.out.print(array[x] + ", ");
System.out.println(array[l-1] + " ]");
}
public static void main(String[] args) {
int ia1[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90};
int ia2[] = { 10, 20, 30, 40, 50, 60, 70, 80, 0};
System.out.println("Removing 40...");
dumpArray(ia1);
// remove 40 from ia1.
for ( int x = 8; x > 3; x--)
ia1[x-1] = ia1[x];
dumpArray(ia1);
System.out.println("\nInserting 99 at first position...");
dumpArray(ia2);
// insert at first position.
for ( int x = 0; x < 8; x++)
ia2[x+1] = ia2[x];
ia2[0] = 99;
dumpArray(ia2);
}
}
Exercise 3 solution
public class Ch9Ex3 {
public static class ManagedArray {
private int[] ARRAY;
private int INUSE;
public ManagedArray(int size) {
INUSE = 0;
ARRAY = new int[size];
}
public int size() {
return ARRAY.length;
}
// add a value at the end;
public int add(int val) {
if ( INUSE >= ARRAY.length )
return -1;
ARRAY[INUSE] = val;
INUSE++;
return INUSE;
}
// get a value at a apecific index.
public int get(int pos) {
/* if pos is out of bounds or there are no
* items in the ARRAY, it is an error.
*/
if ( pos > INUSE || pos < 0 || INUSE == 0 )
return -1;
return ARRAY[pos];
}
// Dump the array. Make it pretty.
public void dumpArray () {
int x, l = ARRAY.length;
System.out.print("[ ");
for ( x = 0 ; x < l - 1 ; x++ )
System.out.print(ARRAY[x] + ", ");
System.out.println(ARRAY[l-1] + " ]");
}
// Delete the number at pos.
public int delete(int pos) {
/*
Length is 9, in use is 9. If we call delete
with pos 2, we loop from 2 to 7. This is due to
running off the end with x+1.
0 1 2 3 4 5 6 7 8
--------------------------------------------
| 11 | 34 | 56 | -3 | 25 | 78 | 98 | 36 | 10 |
--------------------------------------------
x x+1 x x+1
pos
BEGIN END
Array after move. In use is now 8.
0 1 2 3 4 5 6 7 8
--------------------------------------------
| 11 | 34 | -3 | 25 | 78 | 98 | 36 | 10 | 10 |
--------------------------------------------
*/
int x;
/* if pos is out of bounds or there are no
* items in the ARRAY, it is an error.
*/
if ( pos > INUSE || pos < 0 || INUSE == 0 )
return -1;
// Note: if pos == INUSE, no move happens.
// Also, if pos == 0 and INUSE == 1,
// no move happens.
for ( x = pos; x < INUSE - 1; x++)
ARRAY[x] = ARRAY[x+1];
INUSE--;
return INUSE;
}
// Insert val at pos.
public int insert(int pos, int val) {
/*
Length is 9, in use is 8. If we call insert
with pos 3 and val 99, we loop from 7 to 3.
This is due to running off the end with x+1.
0 1 2 3 4 5 6 7 8
--------------------------------------------
| 11 | 34 | -3 | 25 | 78 | 98 | 36 | 10 | 0 |
--------------------------------------------
x x+1 x x+1
pos
END BEGIN
Array after move with INUSE at 9.
0 1 2 3 4 5 6 7 8
--------------------------------------------
| 11 | 34 | -3 | 99 | 25 | 78 | 98 | 36 | 10 |
--------------------------------------------
*/
int x;
/* if the array is exhausted, cannot extend here.
* You can add to one past INUSE, but not past the end
* of the array.
* If pos is out of bounds, it is an error.
*/
if ( INUSE == ARRAY.length || pos > INUSE + 1
|| pos > ARRAY.length || pos < 0 )
return -1;
// Note:
for ( x = INUSE - 1; x >= pos; x--)
ARRAY[x+1] = ARRAY[x];
ARRAY[pos] = val;
INUSE++;
return INUSE;
}
}
public static void main(String[] args) {
int x;
ManagedArray ia = new ManagedArray(10);
// Populate array with 10 random numbers
for ( x = 0; x < ia.size(); x++ )
ia.add((int)(Math.random() * 100 + 1));
System.out.println("Original array.");
ia.dumpArray();
System.out.println("Value at index 3 is " + ia.get(3));
System.out.println("\nDeleting at index 3.");
ia.delete(3);
ia.dumpArray();
System.out.println("\nInserting a zero at index 5.");
ia.insert(5, 0);
ia.dumpArray();
}
}