mdinfotech.net  



Section 1

Java

This is Java.

  • Programming Exercises
  • Regular 100/80/60 Quizzes
  • Short Answer Quizzes
  • Unit Exam
  • Game Project (15% of final mark)

Resources



Do this:
Do these Programming Exercises:
  1. Write a while loop that prints 10 random numbers (all between 1 and 10).
  2. Modify the loop from question 1 so that if one of the random numbers is 5, it prints "You win" and ends the loop.
  3. Write a while loop that prints the digits -100 up to 100.
  4. Write a while loop that prints the digits 100 down to -100.
a) Monty Hall
  1. Watch The Monty Hall Problem.
  2. Watch Monty Hall's Denial of the problem.
  3. Download and play this working version of MontyHall.java
  4. 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.
b) Grade Average
  1. Watch this video on Ending a Loop with a Sentinel Value (C++)
  2. Write a program that reads any number of grades in numerical format, averages them, and then displays the average to the user. Use a while or do...while loop 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.
Bonus: Make both programs Ms. Wear proof. This means I cannot crash it and it will never give weird results, like NaN% or incorrect averages.
Do this:
Do these Exercises:
  1. Complete Control Statements Quiz
  2. Write a for loop that prints the values -1024 to +2048.
  3. Write a for loop that calculates the sum of all numbers from 1 to a user-given number.
  4. 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)
  1. With a partner, complete these Loops Exercises **on paper**.
  2. When you are done, confirm your answers by running the code.
c) A Single For Loop
  1. Ask the user to enter a positive integer n. Use a for loop to print a line of n integers.
    Example Input:
    5
    Output:
    *****
d) Nested For Loops: Stars Triangle
  1. Write and run a program that reads a positive integer n and then prints a triangle of asteriks in that number of rows. Use two nested for loops. For example, if n is 4, then the output would be:
    *
    **
    ***
    ****
    Hints to solve this algorithm:
    1) Print a single star using System.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). Use System.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.
Do this:
Write a program that:
  1. Creates an array of 200 integers
  2. Loads the array with 200 random values between 1 and 100 (Hint: use a for loop)
  3. Prints the elements of the array in order from index 0 to index 199. (Hint: use another for loop)
  4. 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:
  1. Download this incomplete program.
  2. Complete the method absoluteValues() that replaces all the negative numbers in an array of integers with their absolute values.
  3. Complete the method indexOfMinimum() that returns the index of the minimum value stored in an array.
Working with 2D Arrays
  1. Write a method named randomNumbersFill(int [][] a). This method should fill the array with random integers between 0 and 9, inclusive.
  2. 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
    	 
  3. Write a method named findSum(int [][] a)(). This method should calculate and return the sum of all numbers in the array.
  4. 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.

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.

  1. Create a new Eclipse Project. Call your main class FileInputOutput.
  2. Copy and paste File Input and Output Code into your main class.
  3. Copy and paste this list of numbers. Save it into a text file called nums.txt in the bin folder of your Eclipse project.
  4. Run the code. You should see the contents of nums.txt print to the console.
  5. Look into the Eclipse Project folder using Windows Explorer (the file manager on Windows) and notice a new file called output.txt has appeared. Open it, and you should see a duplicate of the numbers in nums.txt. This file was created by your program!
  6. Now uncomment line 21, and write the method sumIntegers(). Run the program.
  7. 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.
  1. Put this four letter list in a file called dictionary.txt.
  2. 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.
  1. Ask the user the question in an Input Dialog Box.
  2. If the word does not have exactly four letters, print an error message in the dialog box and ask the question again.
  3. 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.
  4. 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.

Chars are a type of integer. Chars work with integer addition and comparisons.
          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");
          }
          
Video Lessons
  1. Intro to Change One Letter
  2. How to Change One Letter (with answers to other questions)
  3. 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: wall
Goal Word: boil
wall
mall
mail
hail
tail
toil
boil
 

Program Requirements

Your program must:

  1. 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
    • 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.
  2. 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.
    After each valid move:
    • Display the new word in the console
  3. 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
How to make a move:

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 enter 2 s to change the r to s.

The format to change the letter is considered invalid if:

  1. The number is not an integer between 0 and 3
  2. The letter is not a character between a and z
  3. There is not a space between the number and letter
  4. There is more than one space between the number and letter
  5. The new word is not in the English dictionary

If invalid

  1. show a clear error message in the same input dialog box as the question
  2. require the user to try again
Sample InputOutput
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.
Design Requirement
  1. Use the dictionary and the isValidWord() method from PE 11 to validate all words.
  2. Use getWordFromUser() from PE 11.
Programming Tips
  1. Plan the program first: flow chart it, outline the methods you will need.
  2. Program one step at a time, test it, then move on to the next step.
  3. Design using best practices: break your code into methods, avoid repeated code
Working with Strings
  1. Since you cannot change the individual characters of a String, use a character array to modify letters:
    1. To convert a String to a character array:
      String someString = "this is a string";
      char  someCharacterArray;
      
      someCharacterArray = someString.toCharArray();
                          
    2. To convert a character array to a String:
      someString = new String (someCharacterArray);
                      

Evaluation (/56)

  1. 2 Working Test Cases (/20)
  2. 8 Non-working Test Cases (/16)
  3. Commenting and Formatting (/10)
  4. Efficiency and Design (/10)

To hand in:

  1. In Class Peer Evaluation
  2. Put code in Portfolio
  3. Print code and put in Ms. Wear's Wire In-basket
Based on Change One Letter
Complete the Impacts of Programming assignment on Google Classroom.
Worth 6.7% of FINAL MARK.

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
In Student Share, get the code from "CoinCollectorGameIncomplete.java". Read the instructions in the comments at the top and complete the exercise.

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 Deluxe
Collect 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
    1. Walk me through this part of the program.
    2. What code are you most proud of?
    3. What part did you struggle to understand?
    4. What did you learn while building the game?
Assessment (/100)
Marking Criteria
Tutorial: Make the Coin Chase the Player (Enemy AI)

Right now, your coin moves like this:

  1. It bounces off the walls
  2. It moves using coinDX and coinDY

We’re going to turn it into an enemy that chases the player

1: Understand the Goal

We want the coin to:

  1. Move toward the player’s position
  2. Update every frame (inside gameLoop)
  3. 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:

  1. If coin is left of player - move right
  2. If coin is right of player - move left
  3. 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:

  1. The coin checks where the player is
  2. It moves a little closer
  3. 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