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) {
System.out.println("Flowers for Algernon");
}
}
b)
public class BadCode {
public static void main(String[] args){
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
Answer: 10 / 2
d. 2x - 4
Answer: 2 * x - 4
Location: Arithmetic Operations
public class Question17 {
public static void main(String[] args) {
// this will yield an incorrect answer, because everything is done with
// integer division
System.out.println(4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11));
// the statement above works like this:
// 1/3, 1/5, 1/7, etc.. those all evaluate to 0, due to integer division
// therefore, you have 4 * (1 - 0 + 0 - 0 .. etc) = 4 * 1 = 4
// this will be more accurate because by using 1.0, you're
// forcing Java to do proper floating-point division
System.out.println(4 * 1.0 - 1.0/3 + 1.0/5 - 1.0/7 + 1.0/9
- 1.0/11 + 1.0/13);
}
}
Location: Order of Precedence
a * b > (c + d)
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 |
Correct Java Expression | |
---|---|---|---|
1. | (2)(3) + (4)(5) | (2)(3) + (4)(5) | 2 * 3 + 4 * 5 |
2. | 6 + 18 2 |
6 + 18 / 2 | (6 + 18) / 2 |
3. | 4.5 12.2 - 3.1 |
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) | 4.6 * (3.0 + 14.9) |
5. | (12.1 + 18.9)(15.3 - 3.8) | (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) |
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:
question a)
// 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);
}
}
question b)
// 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);
}
}
question c)
// 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. 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) {
// initialize the bill/tip variables
double billAmount = 35.1;
double tipPercent = 15.0;
// calculate the tip amount
double tipAmount = tipPercent / 100 * billAmount;
// display the amount to tip for this bill
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. 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);
}
}
Trace Chart:
Line # | Variables | Output |
---|---|---|
5 | factor: 2 | -- |
6 | sum: 10 | -- |
7 | -- | sum is 10 |
8 | sum: 10 * 2 = 20 | -- |
9 | -- | sum is now 20 |
10 | sum: 20 * 2 = 40 | -- |
11 | -- | sum is now 40 |
12 | sum: 40 * 2 = 80 | -- |
13 | -- | sum is now 80 |
Output should be:
sum is 10 sum is now 20 sum is now 40 sum is now 80
2. 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);
}
}
Trace Chart:
Line # | Variables | Output |
---|---|---|
5 | factor: 2 | -- |
6 | sum: 10 | -- |
7 | -- | sum is 10 |
8 | sum: 10 * 2 = 20 | -- |
9 | sum: 20 * 2 = 40 | -- |
10 | sum: 40 * 2 = 80 | -- |
11 | -- | sum is now 80 |
12 | -- | sum is now 80 |
13 | -- | sum is now 80 |
Output will be:
sum is 10 sum is now 80 sum is now 80 sum is now 80
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?
**NOTE: using the ■ to denote a space
Location: Using String.format()
Complete the code to display the values below on the console. Display 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. Use the String.format() function to store your formatted string in a String variable called "output":
35 28.29 143.12 .8899
public class FormatQuestion {
public static void main(String[] args) {
// finish this line using String.format():
String output = String.format("%6.2f%n%6.2f%n%6.2f%n%6.2f",
35.0, 28.29, 143.13, .8899);
System.out.println(output);
}
}
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
Question 1
Question 2
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: Types of Errors
For each of the following code segments below:
a. Identify any errors in the code segment.
b. Indicate the category of each error (Compilation Error,
Run-Time error, or Logic Error)
public class SomeErrors {
public void main(String[] args) {
System.out.print("Hi");
System.out.printlm("Hello");
System.out.print("Bye" \n);
}
}
Line 3: main() method header is missing "static" keyword, should
be public static void main(String[] args) - Compilation Error
Line 6: println() method misspelled - Compilation Error
Line 7: new-line character \n is outside the string literal, should be
inside the string literal e.g. "Bye\n" - Compilation Error
public class SomeErrors {
public static void main(String[] args) {
int number;
int value = 1;
number++;
double result = number / value;
System.out.println("Result: " result);
}
}
Line 7: number is not initialized, so you can't use ++ operator -
Compilation Error
Line 8: integer division (number and value are both integers) -
Logic Error
Line 9: missing concatenation operator, should be "Result: " + result
- Compilation Error
public class SomeErrors {
public static void main(String[] args) {
Scanner in = new Scanner();
System.out.println("Enter number of cats.");
number = in.nextInt();
System.out.printf("%4.2f is too many cats.", number);
}
}
Line 5: Scanner constructor method missing source of input, should
be new Scanner(System.in) - Compilation Error
Line 7: number was never declared/defined - Compilation Error
Line 8: format specifier %4.2f doesn't match actual data type of
number argument (number is an int), should be %4d - Runtime Error
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: Parse Methods
Copy the following program. Compile it, and run it. Test the program with each of the input values below, and for each test, describe what happens and why.
Integer.parseInt() will always throw a NumberFormatException if you give it any value that contains a non-digit. Double.parseDouble() will always throw a NumberFormatException if you give it any value that contains a non-digit or more than one decimal point.
public class Conversions {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a value: ");
String strValue = in.next();
int intNum = Integer.parseInt(strValue);
double dblNum = Double.parseDouble(strValue);
System.out.println(intNum + ", " + dblNum);
}
}
Location: Relational Expressions
1.
2.
import java.util.Scanner;
public class MathQuestion {
public static void main(String[] args) {
// create a Scanner for keyboard input
Scanner in = new Scanner(System.in);
// generate two random numbers
int value1 = (int)(Math.random() * 10) + 1;
int value2 = (int)(Math.random() * 10) + 1;
// display the question and get the user's answer
System.out.printf("What is %d + %d?", value1, value2);
int answer = in.nextInt();
// calculate the real answer
int realAnswer = value1 + value2;
// determine if the user is correct
boolean correct = realAnswer == answer;
// display the user's result
System.out.printf("%d + %d = %d is %B%n", value1, value2, answer, correct);
}
}
Location: Comparing Strings
import java.util.Scanner;
public class CompareName {
public static void main(String[] args) {
// create a Scanner for keyboard input
Scanner in = new Scanner(System.in);
// get the user's name
System.out.print("Enter name: ");
String name = in.nextLine();
// display whether or not the name is the same
System.out.println("Do we have the same name? " +
name.equalsIgnoreCase("Wendi"));
}
}
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.
d d false -4
5.
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.
6.
7.
Location: The Conditional Operator
1.
2.
3.
4.
5.
Location: Single-Sided Ifs
1.
2.
Location: Double-Sided Ifs
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
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); }
5
(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:
ERROR NOTE: DISC_COST should be initialized to 4.99 and REG_COST should be initialized to 3.99.
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
Question 1
Question 2
Question 3
Question 4
Location: Data Validation
Question 1:
Question 2:
Question 3:
Question 4:
Question 1:
Question 2:
Question 1:
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; // init counter
// while counter is 10 or less
while (counter <= 10) {
// print counter and its square
System.out.printf("%d %10d%n", counter, Math.pow(counter));
counter++; // next 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--)
public class Question5b {
public static void main(String[] args) {
int counter = 10; // init counter
// while counter 1 or more
while (counter >= 1) {
// print counter and its square
System.out.printf("%d %10d%n", counter, Math.pow(counter));
counter--; // next 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:
Solutions to 5.2, 5.4, and 5.6 can be found on the textbook web site.
Location: Exercises
Question 2:
Location: Exercises
Question 1 (post-test loop):
Question 3:
Question 2:
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.
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:
Question 4:
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.
Ambiguous Invocation for the first and third doStuff() method: both accept a single String argument.
Question 2:
Location: String Processing
Question 1:
Question 2:
Question 3:
Question 4:
Question 5:
Question 6:
Question 6:
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: Array Intro Exercises
Question 1:
Question 2a:
Question 2b:
Location: Coding/Using Arrays
Question 1:
Question 2:
Question 3:
Question 4:
Location: Initializing Arrays
public class ArraysInit {
public static void main(String[] args) {
// hard code an array of course names
String[] courses = {"Computer Programming 1",
"Problem Solving & Programming Logic",
"Mathematics for Computing",
"Web Technologies 1",
"Linux/Unix Operating System",
"Underwater Basket Weaving"};
// display each course name
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) {
// hard code an array of course names
String[] courses = {"Computer Programming 1",
"Problem Solving & Programming Logic",
"Mathematics for Computing",
"Web Technologies 1",
"Linux/Unix Operating System",
"Underwater Basket Weaving"};
// display each course name
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(); }