This page contains all the solutions to the different exercises in the on-line notes pages of the PROG10082 course. Solutions to textbook questions or programming exercises are not listed here (ask your professor where these might be found).
Location: Your First Java Programs - bottom of the page
1.
public class FavouriteFoods
{
public static void main(String[] args)
{
// print my favourite foods
System.out.println("Wendi's Favourite Foods:");
System.out.println("Strawberries");
System.out.println("Chocolate");
System.out.println("Perch");
}
}
2. The minimum number of statements for Question 1 is one! For example:
public class FavouriteFoods
{
public static void main(String[] args)
{
// print my favourite foods
System.out.println("Wendi's Favourite Foods\nStrawberries"
+ "\nChocolate\nPerch);
}
}
3.
public class Tree
{
public static void main(String[] args) {
// print a little tree
System.out.println(" *");
System.out.println(" ***");
System.out.println(" *****");
System.out.println("*******");
System.out.println(" #");
System.out.println(" #");
}
}
Location: Exercises
1. Reformat the following code segments by hand so that they follow proper standards:
a)
public class BadCode {
public static void main(String[] args) {
// print the title of a story/book
System.out.println("Flowers for Algernon");
}
}
b)
public class BadCode {
public static void main(String[] args){
// do some calculations and print the result
System.out.print("6/4*2 is ");
System.out.println(6 / 4 * 2);
}
}
2. Add documentation to each of the corrected code segments above.
a)
/* BadCode
*
* Version 1.0
*
* September 2012
*
* This program displays a book title on the screen.
* Programmed by Wendi Jollymore
*/
public class BadCode {
public static void main(String[] args) {
// display book title
System.out.println("Flowers for Algernon");
}
}
b)
/* BadCode
*
* Version 1.0
*
* September 2012
*
* This program displays an arithmetic
* expression on the screen with its result.
* Programmed by Wendi Jollymore
*/
public class BadCode {
public static void main(String[] args){
// display the expression
System.out.print("6/4*2 is ");
// calculate and display the result
System.out.println(6 / 4 * 2);
}
}
Location: Scientific Notation
For practice, try converting these to scientific notation:
1. 34,982.58 = 3.498258x104
2. .004785 = 4.785x10-3
3. .123467 = 1.23467x10-1
Now try converting these values from scientific notation into regular floating-point numbers:
1. 9.7824 x 103 = 9,782.4
2. 2.222 x 107 = 22,220,000
3. 1.987 x 10-2 = 0.01987
4. 5.5 x 10-4 = 0.00055
Location: Exponential Notation
Convert the following into exponential notation:
1. 34,982.58 = 3.498258e4
2. .004785 = 4.785e-3
3. .123467 = 1.23467e-1
Location: Arithmetic Operations
1. Modulus is often used to find out if a number is even or odd.
How would this work?
Answer: Any number N % 2 will be equal to 0 if the number is even, and
equal to 1 if the number is odd.
2. Rewrite each of the following expressions in proper Java syntax:
a. 3 x 4
Answer: 3 * 4
b. (x + 2)(x - 3)
Answer: (x + 2) * (x - 3)
c. 10 ÷ 2
10 / 2
d. 2x - 4
2 * x - 4
Location: Order of Precedence
1. In the table below there are 5 sets of algebraic expressions and a corresponding incorrect Java expression. Find the errors in the Java expressions and rewrite them correctly.
Algebraic Expression | Incorrect Java Expression | |
---|---|---|
1. | (2)(3) + (4)(5) | (2)(3) + (4)(5) |
2. | 6 + 18 2 | 6 + 18 / 2 |
3. | 4.5 12.2 - 3.1 | 4.5 / 12.2 - 3.1 |
4. | 4.6(3.0 + 14.9) | 4.6(3.0 + 14.9) |
5. | (12.1 + 18.9)(15.3 - 3.8) | (12.1 + 18.9)(15.3 - 3.8) |
2. Evaluate each of the following integer expressions:
a. 20 - 5 / 2 + 3
= 20 - 2 + 3 = 21
b. 20 - 5 / (2 + 3)
= 20 - 5 / 5 = 20 - 1 = 19
c. 10 * (1 + 7 * 3)
= 10 * (1 + 21) = 10 * 22 = 220
d. 15 % 3
= 0
e. 10 + 5 % 2
= 10 + 1 = 11
f. 10 * 5 % 2
= 50 % 2 = 0
3. Evaluate each of the following expressions:
a. 6.0 / 4.0
= 1.5
b. 20.0 - 5.0 / 2.0 + 3.0
= 20.0 - 2.5 + 3.0 = 20.5
c. 20.0 - 5.0 / (2.0 + 3.0)
= 20.0 - 5.0 / 5.0 = 20.0 - 1.0 = 19.0
d. (20.0 - 5.0) / (2.0 + 3.0)
= (15.0) / (2.0 + 3.0) = 15.0 / 5.0 = 3.0
4. Evaluate each of the following expressions:
a. 10.0 + 15 / 2 + 4.3
= 10.0 + 7 + 4.3 = 17.0 + 4.3 = 21.3
b. 10.0 + 15.0 / 2 + 4.3
= 10.0 + 7.5 + 4.3 = 17.5 + 4.3 = 21.8
c. 3 * 6.0 / 4 + 6
= 18.0 / 4 + 6 = 4.5 + 6 = 10.5
d. 20.0 - 5 / 2 + 3.0
= 20.0 - 2 + 3.0 = 18.0 + 3.0 = 21.0
e. 3.0 * 4 % 6 + 6
= 12.0 % 6 + 6 = 0.0 + 6 = 6.0
5. Question 2.17 on page 51:
4 / (3 * (r + 34)) - 9 * (a + b * c) + (3 + d * (2 + a)) / (a + b * d)
Location: Variables
1. Which of the following are valid variable identifiers? For the invalid ones, explain why they're invalid.
VALID / INVALID
headings | headings12 | headings 12 (contains a space) | 12headings (starts with a digit) |
point.x (contains a dot) | pointX | Xpoint | point^x (contains a ^ symbol) |
2. Do question 2.4 on page 40.
The valid identifiers are: miles, Test, $4, apps, x, y, and radius.
The identifiers that are keywords are: class, public, and int.
All the rest are invalid: a++, --a, 4#R, and #44.
Location: Variables
For each of the following statements below, declare a variable and
initialize it to a null value. Use the most appropriate data types and
identifier names.
a. to store a customer's last name
String custLastName = "";
b. to record the number of customers
int numCustomers = 0;
c. to record the customer's outstanding balance
double custBalance = 0.0;
d. to store the customer's phone number
String custPhone = "";
bonus: to record a single keystroke made by the user
char keystroke = '\0';
Location: Assignment Statements
1. Find the errors in each of the following code listings:
// 1. a)
public class Qu2PartA
{
public static void main(String[] args)
{
width = 15 // missing semi-colon, data type
area = length * width; // area, length not declared
System.out.println("The area is " + area);
}
}
Corrected version:
// 1. a)
public class Qu2PartA
{
public static void main(String[] args)
{
double width = 15;
double length = 10;
double area = length * width;
System.out.println("The area is " + area);
}
}
// 1. b)
public class Qu2PartB
{
public static void main(String[] args)
{
int length, width, area;
area = length * width;
length = 20; // both of these 2 stmts should be
width = 15; // before area = length * width
System.out.println("The area is " + area);
}
}
Corrected version:
// 1. b)
public class Qu2PartB
{
public static void main(String[] args)
{
int length, width, area;
length = 20;
width = 15;
area = length * width;
System.out.println("The area is " + area);
}
}
// 1. c)
public class Qu2PartC
{
public static void main(String[] args)
{
int length = 20, width = 15, area;
length * width = area; // backwards!!
System.out.println("The area is " + area);
}
}
Corrected version:
// 1. c) public class Qu2PartC { public static void main(String[] args) { int length = 20, width = 15, area; area = length * width; System.out.println("The area is " + area); } }
2. Do question 2.5 on page 41 and question 2.6 on page 43.
Question 2.5: Identify and fix the errors:
Line 3: the variable k is not defined anywhere. To fix: Declare the variable k before the variable i:
int k = 3; // or whatever value you want int i = k + 2;
Question 2.6: Identify and fix the errors:
Line 3: only i is being defined, j and k don't exist and are not being defined in this statement. To fix:
int i = 2, int j = 2, int k = 2;
OR...
int i = 2; int j = 2; int k = 2;
OR...
int i = 2, int j, int k; j = k = i;
...and there's probably a few other similar solutions, too.
3. Write a program that calculates the amount of money to tip a wait person by coding the following tasks:
Bill Amount: 35.1 Tip%: 15.0 Tip Amount: $5.265
public class Question2 { public static void main(String[] args) { double billAmount = 35.1; double tipPercent = 15.0; double tipAmount = tipPercent / 100 * billAmount; System.out.println("Bill Amount: " + billAmount + "\tTip%: " + tipPercent + "\nTip Amount: $" + tipPercent);
Location: Assignment Statements
1. The code:
public class ConstTest { // constant for the name of the college public static final String COLLEGE_NAME = "Sheridan College"; public static void main(String[] args) { // print out where we work/attend school System.out.println("You attend " + COLLEGE_NAME + "."); // change the name! o.O NOPE COLLEGE_NAME = "Sheridan College Institute of Technology and Advanced Learning"; // print it out again! System.out.println("You should really call it " + COLLEGE_NAME); } }
You should get an error when you compile ("Error: cannot assign a value to final variable COLLEGE_NAME"). The values of constant variables can never change once they're declared and assigned!
Location: Assignment Operators
Determine, without coding a program, the output of the following code segment:
int counter = 1; int increment = 2; System.out.print(counter + " "); counter += increment; System.out.print(counter + " "); counter *= increment; System.out.print(counter + " "); increment /= 2; counter -= increment; System.out.println(counter); System.out.println("increment: " + increment);
Output:
1 3 6 5 increment: 1
Location: Exercises
1. Question 2.24:
14 3
2. Examine the code listing below. What do you think the output should be? Write this down. Then run the program and see if you're correct.
public class Question2 { public static void main(String[] args) { int factor = 2; int sum = 10; System.out.println("sum is " + sum); sum *= factor; System.out.println("sum is now " + sum); sum *= factor; System.out.println("sum is now " + sum); sum *= factor; System.out.println("sum is now " + sum); } }
Output should be:
sum is 10 sum is now 20 sum is now 40 sum is now 80
3. How do you think the output would change if you wrote the program in question 2 like this:
public class Question3 { public static void main(String[] args) { int factor = 2; int sum = 10; System.out.println("sum is " + sum); sum *= factor; sum *= factor; sum *= factor; System.out.println("sum is now " + sum); System.out.println("sum is now " + sum); System.out.println("sum is now " + sum); } }
Output will be:
sum is 10 sum is now 80 sum is now 80 sum is now 80
4.
Question 2.25:
Question 2.26:
7 6 7 7
(In line 2, b receives the value of a before a is incremented)
Location: Formatting Console Output
1. What is the output from each of the following print statements?
**NOTE: using the ■ to denote a space
2. What are the errors in each of the following print statements?
Location: Other Formatting Characters
What is the output from each of the following print statements?
Location: Using String.format()
1. Write the code to declare and initialize two variables for the numerator and denominator of a fraction (initialize each to whatever values you wish, or use the values in the example, below). Write the code that displays the following message dialog:
The result of numerator / denominator should be formatted to 3 decimal places.
import javax.swing.JOptionPane; public class Exercise1 { public static void main(String[] args) { int numerator = 1; int denominator = 3; JOptionPane.showMessageDialog(null, String.format("%d/%d = %.3f", numerator, denominator, ((double)numerator / denominator), "Fractions", JOptionPane.INFORMATION_MESSAGE); } }
2. Write the code to display the values below in a single message dialog box, one value per line. Each value should be formatted to be right-justified, lined up at the decimal point, and showing only one digit after the decimal point:
35 28.29 143.12 .8899
import javax.swing.JOptionPane; public class Exercise1 { public static void main(String[] args) { String output = String.format("%6.2f%n%6.2f%n%6.2f%n%6.2f", 35.0, 28.29, 143.13, .8899); JOptionPane.showMessageDialog(null, output, "Question 2", JOptionPane.INFORMATION_MESSAGE); } }
Location: Using String.format()
1. Use Chapter 5.10 of your textbook or the Math class documentation as a reference. What Math class methods would you use to perform the following tasks:
2. Write a single statement to perform each of the following calculations and store each result in a variable of the appropriate type:
3. Write each of the following expressions as a single Java statement:
a. ![]() |
double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); |
b. ![]() |
double p = Math.sqrt(Math.abs(m - n)); |
c. ![]() |
double sum = a * (Math.pow(r, n) - 1) / (r - 1); |
Location: IPO Charts
1. Define the inputs, processing, and outputs for a program that gives the surface area and volume of a cylinder.
Inputs | cylinder radius cylinder height |
---|---|
Processing | surface area = 2 * PI * radius2
+ height * 2 * PI * radius volume = height * PI * radius2 |
Output | surface area volume |
2. Define the inputs, processing, and outputs for a program that displays the future value of an investment for a principal P at a rate R compounded yearly for n years. The formula for compound interest is final amount = P(1+R/100)n.
Inputs | principal interest rate number of years |
---|---|
Processing | future value = principal * (1 + rate/100)years |
Output | future value of investment |
Location: Exercises
a) Develop a solution for a program that converts a temperature from Fahrenheit to Celsius. (Celsius temperature = 5.0/9.0 * (Fahrenheit temperature - 32.0).
Input | Fahrenheit temperature |
---|---|
Processing | celsius = 5.0/9.0 * (fahrenheit - 32.0) |
Output | Celsius temperature |
b) Develop a solution for a program that calculates a person's target heart rate (a target heart rate is the heart rate you should aim to maintain while you're working out). Use the following formula: Target Heart Rate = .7 * (220 - your age) + .3 * Resting Heart Rate (your resting heart rate is your heart rate while you're not participating in any physical activity).
Input | resting heart rate age |
---|---|
Processing | target heart rate = .7 * (220 - age) + .3 * resting heart rate |
Output | target heart rate |
c) Write a tip calculator that allows a restaurant or bar customer to calculate the amount of a tip to give their wait person. The program should allow the customer to specify the bill amount and the percentage of tip they would like to give.
Input | bill amount, tip percentage |
---|---|
Processing | tip amount = tip percentage / 100 * bill amount |
Output | tip amount |
d) The three ingredients required to make a bucket of popcorn in a movie theatre are popcorn, butter, and a bucket. Write a program that requests the cost of these three items and the price of a serving of popcorn (assume we have only one size). The program should then display the profit.
Input | cost of bucket cost of butter cost of popcorn selling price |
---|---|
Processing | profit = selling price - (cost of bucket + cost of butter + cost of popcorn) |
Output | profit for one bucket of popcorn |
e) You would like to be able to calculate your average grade for all the courses you've taken in first semester. Write a program that prompts you for the grades for the five courses you would have completed in first term. After recording all five grades, display the average grade on the console.
Sample output using sample data:
You entered your five grades as: 85.6 78.9 75.5 90.0 86.5 Your average grade: 83.3
Input | course 1 grade course 2 grade course 3 grade course 4 grade course 5 grade |
---|---|
Processing | average grade = (course 1 grade + course 2 grade + course 3 grade + course 4 grade + course 5 grade) / 5 |
Output | list of grades input average grade |
Location: Input Using Scanner
a)
b)
c)
d)
3)
Location: Characters and Character Operations
1. Write a program that finds the ASCII code for each of the following character values:
public class CharOps { public static void main(String[] args) { int value = 0; char c1 = '7'; value = c1; System.out.println(value); char c2 = '1'; value = c2; System.out.println(value); char c3 = 'a'; value = c3; System.out.println(value); char c4 = 'A'; value = c4; System.out.println(value); char c5 = 'z'; value = c5; System.out.println(value); char c6 = 'Z'; value = c6; System.out.println(value); char c7 = '*'; value = c7; System.out.println(value); } }
2. Open the following chart in a new browser window/tab: Simple ASCII Table.
Location: Explicit Casting
1. How would you use casting to solve the problem in the
TestData example in the first section?
Cast one or both of val1 and val2 into a
double value; you'll also have to declare result as a double:
double result = (double)val1 / val2
2. Using the declaration/initialization statements below, determine the result of each of the following explicit casts.
double dNum1 = 5.5; double dNum2 = 10.2; double dNum3 = 1.1;
Location: Relational Expressions
1.
2.
Scanner in = new Scanner(System.in); int value1 = (int)(Math.random() * 10) + 1; int value2 = (int)(Math.random() * 10) + 1; System.out.printf("What is %d + %d?", value1, value2); int answer = in.nextInt(); int realAnswer = value1 + value2; boolean correct = realAnswer == answer; System.out.printf("%d + %d = %d is %B%n", value1, value2, realAnswer, correct);
Location: Comparing Strings
Scanner in = new Scanner(System.in); System.out.print("Enter name: "); String name = in.nextLine(); System.out.println("Do we have the same name? " + name.equalsIgnoreCase("Freddie"));
Location: Logical Operations
1.
2. Given that:
a = 5
b = 2
c = 4
d = 6
e = 3
What is the result of each of the following relational expressions?
3.
4.
3.2: (try this by hand before checking your answer in your editor!)
true false false true true true
3.3:
Neither set of statements is valid. If you go back to the lesson on Casting and Converting, you'll notice in the conversion chart that you can't cast a boolean into any primitive type, and you can't cast any primitive type into a boolean.
5.
3.18: Assuming x is 1:
(true) && (3 > 4) = true && false = false
!(x > 0) && (x > 0) = !(true) && true = false && true = false
(x > 0) || (x < 0) = true || false = true
(x != 0) || (x == 0) = true || false = true
(x >= 0) || (x < 0) = true || false = true
(x != 1) == !(x == 1)= false == !(true) = false == false = false
3.19:
a) num >= 1 && num <= 100
b) num >= 1 && num <= 100 || num < 0
3.20:
a) Math.abs(x - 5) < 4.5
b) Math.abs(x - 5) > 4.5
3.21:
3.22:
a. x % 2 == 0 && x % 3 == 0
b. x % 6 == 0
In other words, is a number that is both evenly divisible by 2 and evenly divisible by 3, also evenly divisible by 6? Yes, since 2 and 3 are both factors of 6.
3.23:
x >= 50 && x <= 100 if x is 45, 67, or 101
x is 45:
45 >= 50 && 45 <=100 = false && true = false
x is 67:
67 >= 50 && 67 <= 100 = true && true = true
x is 101:
101 >= 50 && 101 <= 100 = true && false = false
3.24:
(x < y && y < z) is true (x < y || y < z) is true !(x < y) is false (x + y < z) is true (x + y > z) is false
3.25:
age > 13 && age < 18
3.26:
weight > 50 || height > 60
3.27:
weight > 50 && height > 60
3.28:
weight > 50 ^ height > 60
6.
d d false -4
7.
a)
false
2
This is probably what you would expect to get:
The entire expression evaluates to false, and x has a value of 2 after
the statement executes: (x >= 1) is true, but (x > 1) is false, so the entire
expression is false. After the evaluation of the conditions are complete, x
increments by 1 and becomes 2.
b)
false
1
This may not be the output you expected:
The expression evaluates to false, but notice that the value of x after
this expression executes is 1. This is because of the short-circuiting of the
Java && operator: Since the first condition (x > 1) is false, Java doesn't
even bother checking the second condition, so therefore the x++ is never
executed.
8.
9.
Location: The Conditional Operator
1.
2.
3.
Location: Single-Sided Ifs
1.
2.
3. (textbook questions 3.4 and 3.5 page 80)
3.4
if (y > ) { x = 1; }
3.5
if (score > 90) { pay *= 1.03; // pay = pay + (pay * .03) or pay = pay * 1.03 }
Location: Double-Sided Ifs
Textbook questions 3.6 and 3.7 page 81:
3.6
if (score > 90) { pay *= 1.03; } else { pay *= 1.01; }
3.7 a)
If number is 30:
30 is even 30 is odd
(there's no braces so the 2nd println() will execute regardless)
If number is 35:
35 is odd
3.7 b)
If number is 30:
30 is even
If number is 35:
35 is odd
Programming Questions:
1.
2.
3.
4.
5.
6.
7.
8.
9.
Location: Multi-Sided Ifs
1. a. What would the output be if the user entered a final grade of 48? F
1. b. What would the output be if the user entered a final grade of 55? D
1. c. What would the output be if the user entered a final grade of 85? D
1. d. Why doesn't this program do what it's supposed to do? How would you rewrite it correctly? It doesn't work because the range check is not done properly. Since you're starting from the bottom and going up to higher values, you should be comparing grade to the highest value in each range.
Question 2:
Question 3:
Location: Switch Statement
Textbook questions 3.30 and 3.31 page 103:
3.30
After the code is executed, y is 2 (both case 6 and default are executed)
Rewrite using if-else (rewrote as it executes):
int x = 3; int y = 3; if (x + 3 == 6) { y = 1; } y += 1; // executes regardless of condition value
Rewrite as an else-if properly:
int x = 3; int y = 3; if (x + 3 == 6) { y = 1; } else { y += 1; }
3.31
After the code segment is executed, x is 17.
Rewrite as switch:
int x = 1; int a = 3; switch (a) { case 1: x == 5; break; case 2: x += 10; break; case 3: x += 16; break; case 4: x += 34; }
1.
2.
3.
Location: Nested Selections
1. What is the output of each of the following code segments:
a)
int x = 5; int y = 10; int z = 2; if (x > y) { System.out.println("twice x is " + (x * 2)); if (x * z == y) { System.out.println("xz equals y"); } } else { System.out.println(y /= z); }
0
(the first condition x > z is false, therefore it jumps to that
if's matching else block and prints y /= z)
b)
int x = 5; int y = 10; int z = 2; if (x > y) { System.out.println("twice x is " + (x * 2)); } if (x * z == y) { System.out.println("xz equals y"); } else { System.out.println(y /= z); }
xz equals y
(the braces have moved around in this question: the if (x * z == y) is no
longer inside the if (x > y) block, so it's evaluated regardless of
the truth value of x > y)
Question 2:
Question 3:
Question 4:
Question 5:
Location: Errors with Selections
Do exercises 3.11 to 3.14 on page 86-87.
3.11
Code segment (a) is hard to read so you might want to re-write it using proper indentation, first!
Which are equivalent? (a), (c), and (d) are equivalent to each other.
(a) and (d) are not correctly indented (they should look exactly like (c)); (b) and (c) are correctly indented.
3.12
boolean newLine = count % 10 == 0;
3.13
Both (a) and (b) are correct syntactically and logically.
(b) is better because it's more efficient. With (a), the computer will execute both if-statements and thus evaluate both conditions, whereas in (b) it will evaluate only one condition and only have to move to the else if the condition is false: Therefore, (a) is more work than (b).
3.14
Segment (a):
If number is 14:
14 is even
If number is 15:
15 is is a multiple of 5
If number is 30:
30 is even
30 is a multiple of 5
Segment (b):
If number is 14:
14 is even
If number is 15:
15 is a multiple of 5
If number is 30:
30 is even
(The key here is that in (a) both if statements can be executed if both conditions are true. In (b), the if-else block is only executed if the if-block condition is false.)
Location: Confirm Dialog
Location: Data Validation
Question 1:
Question 2:
Question 3:
Question 4:
Question 4:
Location: While Loops
1. For what values do each of these loops terminate?
2. a. What do you think is the output of this loop if the user enters the value 4?
System.out.print("Enter a value to count to:"); int number = keysIn.nextInt(); int counter = 1; while (counter <= number) { System.out.print(counter + " "); counter++; } System.out.println("\nDone!");
Solution:
1 2 3 4
Done!
2. b. How would you modify this program so that the output appears instead as:
1 2 3 4 Done!
Solution: Change the print() inside the loop to a println().
3. What is the output of the following code segment?
int counter = 1; int sum = 0; while (counter <= 5) sum += counter++; System.out.println(sum);
Solution:
15
4. What's wrong with the following program?
public class LoopProblem { public static void main(String[] args) { // print from 1 to 10 by 2's int counter = 1; while (counter != 10) { System.out.println(counter); counter += 2; } } }
Solution: You have an endless loop because counter will never be equal to 10.
5. a. Write a loop that prints the numbers from 1 to 10 with their squares, like this:
1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100
Solution:
public class Question5a { public static void main(String[] args) { int counter = 1; while (counter <= 10) { System.out.printf("%d %10d%n", counter, Math.pow(counter)); counter++; } } }
5. b. How would you make the loop do the same output backwards (from 10 to 1)?
Initialize the counter to 10
Change the loop condition to counter >= 1
Change the increment to a decrement (counter--)
6. Write a while loop that counts from 1 to 20 by 2's on one line:
2 4 6 8 10 12 14 16 18 20
public class Question6 { public static void main(String[] args) { int counter = 2; while (counter <= 20) { System.out.printf("%d ", counter); counter += 2; } } }
This will work, too:
public class Question6 { public static void main(String[] args) { int counter = 0; while (counter < 20) { counter += 2; System.out.printf("%d ", counter); } } }
7. What is the output of each of the following loops?
Example 1:
4 3 2 1
Example 2:
1 2 3 4
Example 3:
(no output)
Example 4:
3 2 1 0
Example 5:
9 8 7 6 5
Example 6:
1, 2 2, 1 3, 0 4, -1 x: 5 y:-1
Location: Do-While Loops
1. What's the output of each of the following code segments:
Example 1:
4 3 2 1
Example 2:
9 8 7 6 5 4
Example 3:
1
Question 2a:
Question 2b:
Question 2c:
Question 3 (post-test loop):
Question 3:
Solutions to 5.2, 5.4, and 5.6 can be found on the textbook web site.
Location: For Loops
1. What's the output of the following code segments:
a.
0, 1, 2, 3, 4, After the loop, i is 5
b.
0 4 8 12 16 20
c.
1 4 7 10 13 16 19
d.
20 16 12 8 4 0
Question 2:
Question 3:
Location: Nested Loops
1. What's the output of each of the following code segments:
Example a.
0: 0 0 1: 1 2 2: 2 4 3: 3 6 4: 4 8 5: 5 10
Example b.
0: 0 0 0 1: 3 2 1 2: 6 4 2 3: 9 6 3 4: 12 8 4 5: 15 10 5
Question 2:
Question 3:
Question 4:
Location: Nested Structures
Question 1:
Question 2:
Location: More Loop Exercises
Question 1:
Question 2:
Question 3:
Solutions to 5.8, 5.10, 5.16, 5.18, 5.24, and 5.30 can be found on the textbook web site.
Location: Intro to Methods
Question 1:
Question 2:
3.
I have some methods: This is method one. This is method two. Going back to main... That's all!
Question 4:
Question 5:
Location: Arguments/Parameters
Question 1:
2. If you try to pass a String into the guessAge() method, you get an error because the method is expecting an integer, but instead you passed it a String.
Location: Multiple Arguments/Parameters
1.
2.
6.12: On line 3, the 2 arguments are reversed: the method accepts a String, then an int (see line 6) but line 3 is passing in an int argument, then a String argument. To correct it, use:
nPrintln("Welcome to Java!", 5);
Additionally, inside the nPrintln() method, the int argument is named "n" but there is a new local variable "n" being declared on line 7. I will assume they don't need the local variable at all so to fix it, remove line 7.
6.13: Pass-by-value means that a copy of an argument's value is passed into a method parameter variable, not the original. The effect is that you can then modify the parameter variable inside the method and it has no effect at all on the original argument variable.
Output of a) 2
Output of b)
2 2 4 2 4 8 2 4 8 16 2 4 8 16 32 2 4 8 16 32 64
Output of c)
Before the call, variable times is 3 n = 3 Welcome to Java! n = 2 Welcome to Java! n = 1 Welcome to Java! After the call, variable times is 3
Output of d)
1 2 1 2 1 4 2 1 i is 5
Question 3:
Question 4:
Location: Return Values
1. If you change the "perim" variable's data type to an int or to String, your program won't compile because calcPerimSquare() returns a double, and you can't put a double into an int or a String.
2. The two statements are different in that the first one doesn't store the return value anywhere - the perimeter returned by the method is not stored or output. The second statement does store the method's return value in a variable, so it can be used later.
Question 3a:
Question 3b:
4. You can find the solutions to these questions on the textbook web site.
Question 5:
Location: Variable Scope
1.
in main: 1. 1 m1: 5 6 2. 1 m2: 10 3. 1
2. a)
n is 10 now n is 0 num is 10
You get this output because when you pass the argument "num" into the doSomething() method into parameter "n", you are only passing a copy of the value ("pass by value"). When you modify the parameter n inside the doSomething() method, the argument num is not affected.
This is true of all primitive variables: they are passed by value.
2. b)
2 4 6
You get this output because when you pass an object into a method (remember, an array is a type of object), the argument's memory address is passed into the parameter. So for example, if the nums array is stored at address FF88, then FF88 is passed into the parameter "array". This means that when you access the parameter "array" inside the doSomething() method, you are going to the same array in memory that nums is pointing to. In the case of objects, you "pass by reference", which means you pass the argument's address/reference into the parameter. The effect of this is that you can modify the object inside the method via its parameter variable.
Location: Method Overloading
1.
6.16: Ambiguous Invocation: both methods have a single int parameter.
6.17: a) the second method is the best match because we're passing 2 ints and the second method accepts an int and a double. b) will also execute the second method, since it's an exact match. c) will execute the first method, since it's an exact match.
2.
Ambiguous Invocation for the first and third doStuff() method: both accept a single String argument.
Question 3:
Location: String Processing
Question 1:
Question 2:
Question 3:
Question 4:
Question 5:
Question 6:
Question 7:
Location: String Comparison
1.
2.
Question 1:
Question 2:
Location: Array Intro Exercises
1. For each of the following, declare an array with an appropriate name and type and allocate an appropriate amount of storage.
double[] grades = new double[100];
String[] names = new String[10];
double[] temperatures = new double[50];
int[] birthYears = new int[25];
String[] prodIds = new String[200];
int[] numStudents = new int[5];
2. Fill in the elements for the values[] array (it has 10 elements) as the following code executes:
int counter = 1; values[0] = 10; values[counter] = counter; counter++; values[5] = counter; values[9] = values[5] + counter; values[counter] = values[9] - values[1]; values[9] += ++counter;
Array: values[10]
10 | 1 | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 4 3 |
Location: Coding/Using Arrays
Question 1:
Question 2a:
Question 2b:
Question 3:
Question 4:
Question 5:
Question 6:
Location: Initializing Arrays
public class ArraysInit { public static void main(String[] args) { String[] courses = {"Computer Programming 1", "Problem Solving & Programming Logic", "Mathematics for Computing", "Web Technologies 1", "Linux/Unix Operating System", "Underwater Basket Weaving"}; for (int i = 0; i < courses.length; i++) { System.out.println(courses[i]); } } }
Location: For-Each Loop
public class ArraysInit { public static void main(String[] args) { String[] courses = {"Computer Programming 1", "Problem Solving & Programming Logic", "Mathematics for Computing", "Web Technologies 1", "Linux/Unix Operating System", "Underwater Basket Weaving"}; for (String c : courses) { System.out.println(c); } } }
Location: Parallel Arrays
Question 1:
Question 2:
Location: Passing/Returning Arrays
2. a)
Before: 1. 5, 2. 2 In Swap: 1. 2, 2. 5 After: 1. 5, 2. 2
2. b)
Before: 1. 5, 2. 2 In Swap: 1. 2, 2. 5 After: 1. 2, 2. 5
2. c) In (a), the argument values are copied into the parameter variables, so when the parameter variables are swapped, it has no effect on the original arguments. In (b), you're passing the memory address of the array, not a copy of the array values. Therefore, when you swap the 2 array elements, you're modifying the actual array declared in the main() method.
In general, when you pass primitives, you're passing a copy of the values into the parameter variables (pass by value). When you pass objects, you're passing the address/reference of the argument object into the parameter variables, which means the parameter and argument are both referring to the same object in memory (pass by reference).
Location: Exceptions Intro
Revisit your program that calculates the difference between 2 amounts of time.
Location: Exceptions with Wrapper Classes
a) What is the name of the exception that is thrown when this code runs, and what line causes the exception?
NumberFormatException, on the parseInt() line.
b) What happens if you use strValue1 as the parseInt() method's argument instead of strValue2? Why does this happen?
You get the same exception, because strValue1 is a floating-point number; a floating-point number can't be parsed into an int because of the decimal point (ints can only have digits).
c) What exception is caused if you change the last line to:
double dblValue = Double.parseDouble(strValue2);
Same exception. A double can only be digits and one decimal point, so parseDouble() will throw a NumberFormatException if you try to pass it anything invalid.
d) What is the output of the following code?
String strValue1 = "2.5"; double dblValue = Double.parseDouble(strValue1); System.out.println(dblValue);
2.5
Location: More Exceptions Exercises
Question 1a:
Question 1b:
Location: More Data Validation
Location: Demonstration of Objects
myAcct.withdraw(800); myAcct.setRate(5.4); System.out.println(myAcct); // exception is thrown here: myAcct.withdraw(1500);
Location: OOP Exercises
1.
MP3 Player
Properties:
status (on/off), current track, # of tracks,
colour, model, brand, etc.
Methods:
play(), stop(), skip(), turnOn(), turnOff(), etc.
Sample objects:
the old player you bought 13 years ago, your
mom's mp3 player she wears in the gym
Car
Properties:
make, model, colour, number of doors,
engine type, engine status, etc.
Methods:
accelerate(), decelerate(), start(),
changeGear(), etc.
Sample objects:
your car, your dad's car, the car you crashed
into a snow bank
Student
Properties:
student id, first name, last name, program,
gpa, address, phone number, email address,
current term, etc.
Methods:
changeProgram(), register(), calculateGpa(),
dropCourse(), printTranscript(), etc.
Sample objects:
you!
2.
3.
Location: Exercises
1.
2.
3.
Location: Exercises
2.
3.
4.
Location: Exercises
1. What would make 2 Room objects equal? It can depend on context. For example, in a program that is planning blueprints, two rooms would only be considered equal if the length of one room equaled the length of the second room, and the width of one room equaled the width of the second room. For example, if room1 had a length of 10 and a width of 20 and room2 had a length of 10 and a width of 20, then those 2 rooms would be equal:
public boolean equals(Object obj) { Room room = (Room)obj; return room.getLength() == this.length && room.getWidth() == this.width; }
Note that we have to use the accessors for the room variable because the width and length instance variables have private access inside the room class. However, for the current (this) room, we're inside the class itself so it's ok to refer to length and width directly.
What if room1 had a length of 5 and a width of 15, and room2 had a length of 15 and a width of 5? In this case, they would not be equal because you can't take a 5 x 15 room and replace it on a blueprint with a 15 x 5 room: they occupy the space differently. However, what if your room class was being used in a Health & Safety application that kept track of rooms and their occupancy? In that case a 5 x 15 room would be the same as a 15 x 5 room because they would both have the same occupancy, required number of doors and emergency exits, etc. In that case, you could simply compare the areas of the 2 rooms:
public boolean equals(Object obj) { Room room = (Room)obj; return room.calcArea() == this.calcArea(); }
There are probably other answers, but there's the 2 most common ones.
2. What would make 2 Time objects equal? Since this Time class models a time on a clock, 2 times would be equal if both of their hours were equal, both their minutes were equal, and both their seconds were equal. Even better, you could just compare the total seconds of each time and you'd have a little less work to do:
public boolean equals(Object obj) { Time time = (Time)obj; return time.calcTotalSeconds() == this.calcTotalSeconds(); }