Section 1
This is Java.
- Programming Exercises
- Regular 100/80/60 Quizzes
- Short Answer Quizzes
- Unit Exam
- Game Project (15% of final mark)
- Watch and code along with Java While Loop
- Optional: Read this w3 While Loop.
- Write a while loop that prints 10 random numbers (all between 1 and 10).
- Modify the loop from question 1 so that if one of the random numbers is 5, it prints "You win" and ends the loop.
- Write a while loop that prints the digits -100 up to 100.
- Write a while loop that prints the digits 100 down to -100.
- Watch The Monty Hall Problem.
- Watch Monty Hall's Denial of the problem.
- Download and play this working version of MontyHall.java
- Modify this game so that the user can play repeatedly in a single run of the program. Count the number of times the player wins, and print the percentage of wins at the end of the program.
- Watch this video on Ending a Loop with a Sentinel Value (C++)
- Write a program that reads any number of grades in numerical format, averages them,
and then displays the average to the user. Use a
whileordo...whileloop to enter grades and a sentinel variable to indicate when to stop entering grades. Allow the program user to determine when to stop entering the grades.
- Watch and code along with this video on the For Loop
- Optional: Read this Going Loopy Tutorial.
- Complete Control Statements Quiz
- Write a for loop that prints the values -1024 to +2048.
- Write a for loop that calculates the sum of all numbers from 1 to a user-given number.
- Use a for loop to display the multiplication table from 1 to 12 for a user-given number (e.g., 7 => 1x7 = 7, 2x7 = 14, ..., 7x12 = 84)
- With a partner, complete these Loops Exercises **on paper**.
- When you are done, confirm your answers by running the code.
- Ask the user to enter a positive integer
n. Use a for loop to print a line ofnintegers.
Example Input:5
Output:*****
- Write and run a program that reads a positive integer
nand then prints a triangle of asteriks in that number of rows. Use two nestedforloops. For example, if n is 4, then the output would be:* ** *** ****
Hints to solve this algorithm:
1) Print a single star usingSystem.out.print("*").
2) Get the program to print n stars on one line (a single for loop).
3) Then get it to print an nxn square of stars (another for loop around the first for loop). UseSystem.out.println("");to add a hard return where you need one.
4) Now change only one thing in the program will give you the triangle you seek.
NOTE: Solutions with two for loops that are not nested, or with only one for loop will not be accepted.
- Watch Arrays
- Optional - Read Hurray for Arrays.
- Creates an array of 200 integers
- Loads the array with 200 random values between 1 and 100 (Hint: use a for loop)
- Prints the elements of the array in order from index 0 to index 199. (Hint: use another for loop)
- Prints the elements of the array in REVERSE order from index 199 to index 0. (Hint: use a 3rd for loop)
Theory: When a variable with primitive data type is passed to a method, it is 'pass by value', which means a copy of the variable is passed into the method. When an array or object is passed to a method, thereference is 'passed by value', which means a copy of its reference is passed into the method. If the method modifies an array that has been passed in, the original array gets modified.
Do this:- Watch Passing Arrays
- Read this: Passing to Methods.
- Download this incomplete program.
- Complete the method
absoluteValues()that replaces all the negative numbers in an array of integers with their absolute values. - Complete the method
indexOfMinimum()that returns the index of the minimum value stored in an array.
- Write a method named
randomNumbersFill(int [][] a). This method should fill the array with random integers between 0 and 9, inclusive. - Write a method named
print2DArray(int[][] a). This method should display the array in the console in a grid format, similar to the example below::1 2 3 4 0 9 4 3 2 6 4 3 2 1 5 3 4 2 0 9 5 6 7 8 5 3 7 5 8 1 8 7 6 5 0 8 9 5 7 3 5 6 7 8 5 3 7 5 8 1 0 9 8 0 5 3 2 5 3 7 4 3 2 1 5 3 4 2 0 9 7 2 0 8 9 2 6 4 6 5 1 0 7 9 3 5 7 4 6 3 0 5 4 9 4 9 0 5 3 5 - Write a method named
findSum(int [][] a)(). This method should calculate and return the sum of all numbers in the array. - In the main method:
- Declare the array
a. - Call
randomNumbersFill(a)to populate it. - Call
print2DArray(a)to display it. - Call
findSum(a)and store the returned value in a variable named sum. - Print the result to the console in the following format:
The sum of the values is 448.
- Declare the array
In this assignment, you will learn to read data from a file, process the data, and write data to a file. The skills learned here will be required to complete Assignment 2.
Watch Ms Wear's Lesson on File I/O (Input/Output) to complete this exercise.
- Create a new Eclipse Project. Call your main class
FileInputOutput. - Copy and paste File Input and Output Code into your main class.
- Copy and paste this list of numbers. Save it into a text file called
nums.txtin the bin folder of your Eclipse project. - Run the code. You should see the contents of nums.txt print to the console.
- Look into the Eclipse Project folder using Windows Explorer (the file manager on Windows) and notice a new file called
output.txthas appeared. Open it, and you should see a duplicate of the numbers in nums.txt. This file was created by your program! - Now uncomment line 21, and write the method
sumIntegers(). Run the program. - It should print the sum of the values in the console. Check with other students to see if your sums agree.
Method 1: isValidWord(String word)Watch this video lesson on Writing the Dictionary to write a method called
isValidWord() which accepts one string and returns true if it is a valid 4 letter English word.
- Put this four letter list in a file called dictionary.txt.
- Format the dictionary so that the first line contains all the words beginning with a, the second line contains all the words beginning with b, and so on.
Method 2: getWordFromUser(String question)Write a method called
getWordFromUser(String question) with a parameter that is the question to ask the user.
- Ask the user the question in an Input Dialog Box.
- If the word does not have exactly four letters, print an error message in the dialog box and ask the question again.
- Use
isValidWord()to determine if the word is in the dictionary. If not, print an error message in the dialog box and ask the question again. - If the word is four letters and valid, return it to the calling method.
Write the Test Driver
Write a test driver that proves your methods work.
char initial = 'k';
int numValue = (int)initial;
System.out.println(initial + " has numerical value " + numValue);
if (initial < 'a' || initial > 'z') {
System.out.println("initial is not a letter");
}
- Intro to Change One Letter
- How to Change One Letter (with answers to other questions)
- Writing the Dictionary
Overview
You will create a two-player word game where players take turns changing one letter at a time to transform a start word into a goal word.
- All words must be valid 4-letter English words
- Each move must change exactly one letter
Example Game
Start Word: wallGoal Word: boil
wall mall mail hail tail toil boil
Program Requirements
Your program must:
- Game Setup
- Player 1 enters a start word into an input dialog box
- Must be:
- 4 letters
- A valid English word (from the dictionary file)
- Display in console
- Must be:
- Player 2 enters a goal word into an input dialog box
- Must be:
- 4 letters
- A valid English word (from the dictionary file)
- Do NOT display immediately in the console, display it at the end if the user wins.
- Must be:
- Player 1 enters a start word into an input dialog box
- Game Loop Play
Players alternate turns:- Player 1 enters a move into an input dialog box
- Player 2 enters a move into an input dialog box
- Repeat until:
- The goal is reached, OR
- the user clicks CANCEL
- Show the current word and the goal word in the dialog box to help the user plan their move.
- Display the new word in the console
- Winning the Game
- When the goal word is reached:
- Display the final word
- Display:
- The winner (Player 1 or Player 2)
- The total number of valid moves
- End the program
To change a letter, the user must specify the position of one letter to change (0 for the first letter, 1 for the second letter etc), followed by a space, followed by an uppercase OR lowercase letter to change it to in order to make a new word.
Example
Start Word: care
New Word: case
The user would enter2 sto change the r to s.
The format to change the letter is considered invalid if:
- The number is not an integer between 0 and 3
- The letter is not a character between a and z
- There is not a space between the number and letter
- There is more than one space between the number and letter
- The new word is not in the English dictionary
If invalid
- show a clear error message in the same input dialog box as the question
- require the user to try again
| Sample Input | Output |
|---|---|
wAlL boil 0 m 2 i 0 H 0 t 1 o 0 B |
wall mall mail hail tail toil boil Player 2 wins in 6 valid moves. |
- Use the dictionary and the
isValidWord()method from PE 11 to validate all words. - Use
getWordFromUser()from PE 11.
- Plan the program first: flow chart it, outline the methods you will need.
- Program one step at a time, test it, then move on to the next step.
- Design using best practices: break your code into methods, avoid repeated code
- Since you cannot change the individual characters of a String, use a character array to modify letters:
- To convert a String to a character array:
String someString = "this is a string"; char
someCharacterArray;
someCharacterArray = someString.toCharArray();
- To convert a character array to a String:
someString = new String (someCharacterArray);
- To convert a String to a character array:
Evaluation (/56)
- 2 Working Test Cases (/20)
- 8 Non-working Test Cases (/16)
- Commenting and Formatting (/10)
- Efficiency and Design (/10)
To hand in:
- In Class Peer Evaluation
- Put code in Portfolio
- Print code and put in Ms. Wear's Wire In-basket
25 Multiple Choice Questions
Focuses on material and algorithms from this unit
- Loops Exercises
- Methods
- Arrays (1d and 2d)
- File I/O
- Nested for loops (stars program)
- Array manipulation
- Sum a number of values (Grades Average)
- Sentinel Value (Grades Average)
- Passing Arrays to Methods
- Finding minimum location in an array (Passing Arrays to Methods)
- All algorithms from Assignment 2
You will be assigned a partner to complete one of the following projects using CoinCollectorGameIncomplete.java as the basis of your project.
Level 1: Coin Collector DeluxeCollect coins, avoid rocks, reach score goal.
Skills: collision, score, multiple objects
Level 2: Zombie Survival
Avoid enemies moving randomly.
Skills: enemy movement, health, losing screen
Level 3: Frogger Style Game
Cross road while avoiding cars.
Level 4: Two Player Battle Game
WASD vs Arrow Keys.
Milestone 1: (date on classroom)
- at least one image is being used instead of the square player and circle coin
- at least one *new* feature is added to the functionality (that is not part of original code: square player, animated coin, collisions, scoring)
- your game has one additional game state (could be instructions, high score, a new level, or ?)
- both partners will be asked to reflect on the code. Teacher will assess your individual understanding of the code. Example questions
- Walk me through this part of the program.
- What code are you most proud of?
- What part did you struggle to understand?
- What did you learn while building the game?
Marking Criteria
Right now, your coin moves like this:
- It bounces off the walls
- It moves using
coinDXandcoinDY
We’re going to turn it into an enemy that chases the player
1: Understand the Goal
We want the coin to:
- Move toward the player’s position
- Update every frame (inside
gameLoop) - Feel like it’s “hunting” the player
2: Replace the Movement Logic
Old Code (delete this from moveCoin())
coinX = coinX + coinDX;
coinY = coinY + coinDY;
// bounce off walls
if (coinX <= 0 || coinX >= WIDTH - coinSize) {
coinDX = -coinDX;
}
if (coinY <= 0 || coinY >= HEIGHT - coinSize) {
coinDY = -coinDY;
}
New Idea
We compare positions:
- If coin is left of player - move right
- If coin is right of player - move left
- Same idea for up/down
Write the New moveCoin() Method
Replace your entire method with this:
public void moveCoin() {
int speed = 5;
// Move horizontally toward player
if (coinX < playerX) {
coinX = coinX + speed;
} else if (coinX > playerX) {
coinX = coinX - speed;
}
// Move vertically toward player
if (coinY < playerY) {
coinY = coinY + speed;
} else if (coinY > playerY) {
coinY = coinY - speed;
}
}
4: What This Does
Every frame:
- The coin checks where the player is
- It moves a little closer
- This creates a simple **AI chasing behavior
5: Make It Better (Optional Upgrades)
Try these improvements:
1. Make enemy faster over time
int speed = 3 + score;
2. Make enemy slightly “imperfect” (less robotic)
int speed = 5;
if (Math.random() < 0.8) { // 80% chance to move
if (coinX < playerX) coinX += speed;
else if (coinX > playerX) coinX -= speed;
if (coinY < playerY) coinY += speed;
else if (coinY > playerY) coinY -= speed;
}
3. Change goal: Survive instead of collect
Instead of increasing score on collision, you could:
- End the game when the coin touches the player