0% found this document useful (0 votes)
232 views17 pages

Touchstone JAVA Journal Sample

Uploaded by

STEPHEN MWANGI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
232 views17 pages

Touchstone JAVA Journal Sample

Uploaded by

STEPHEN MWANGI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

JAVA Final Project Sample Submission

Java Journal Template


Directions: Follow the directions for each part of the journal template. Include in your response
all the elements listed under the Requirements section. Prompts in the Inspiration section are
not required; however, they may help you to fully think through your response.
Remember to review the Touchstone page for entry requirements, examples, and grading
specifics.

Name: Sophia Student


Date: 05/15/2023
Final IDE Program “Share” Link:
https://onlinegdb.com/oVugPTdKWb
Complete the following template. Fill out all entries using complete sentences.

1
PART 1: Defining Your Problem

Task
State the problem you are planning to solve.

Requirements
● Describe the problem you are trying to solve.
● Describe any input data you expect to use.
● Describe what the program will do to solve the problem.
● Describe any outputs or results the program will provide.

Inspiration
When writing your entry below, ask yourself the following questions:
● Is your problem clearly defined?

● Why do you want to solve this particular problem?

● What source(s) of data do you believe you will need? Will the user need to supply that data,
or will you get it from an external file or another source?
● Will you need to interact with the user throughout the program? Will users continually need to
enter data in and see something to continue?
● What are your expected results or what will be the end product? What will you need to tell a
user of your program when it is complete?

Casino craps is a dice game in which players bet on the outcome of the roll of a pair of dice. The
problem to solve is to help a user better understand the odds of winning and losing at casino craps at
an actual casino. I will create a simulation of the craps game to solve this problem. When executed,
the program will first provide a sample game as an example for the user. Second, the program will
ask the user to input the number of games to play. The program will play the requested number of
games. After the last game is played, the program will output (display) the results of the games. The
program will store a record of the simulations in an external log file. By playing the game multiple
times and reviewing the statistics, users will get a better understanding of their chances of winning.

2
PART 2: Working Through Specific Examples

Task
Write down clear and specific steps to solve a simple version of your problem you identified in Part 1.

Requirements
Complete the three steps below for at least two distinct examples/scenarios.
● State any necessary input data for your simplified problem.
● Write clear and specific steps in English (not Java) detailing what the program will do to solve
the problem.
● Describe the specific result of your example/scenario.

Inspiration
When writing your entry below, ask yourself the following questions:
● Are there any steps that you don’t fully understand? These are places to spend more time
working out the details. Consider adding additional smaller steps in these spots.
● Remember that a computer program is very literal. Are there any steps that are unclear? Try
giving the steps of your example/scenario to a friend or family member to read through and
ask you questions about parts they don’t understand. Rewrite these parts as clearly as you
can.
● Are there interesting edge cases for your program? Try to start one of your
examples/scenarios with input that matches this edge case. How does it change how your
program might work?

Scenario 1: Player loses on first roll:

1. Roll two six-sided random dice for the first time, getting a 1 and a 2.
2. Add the values on the top of the two dice, getting 3.
3. The player loses the game.

Scenario 2: Player wins on first roll:

1. Roll two six-sided random dice for the first time, getting a 3 and a 4.
2. Add the values on the top of the two dice, getting 7.
3. The player wins the game.

Scenario 3: Player loses on a few rolls of the dice:

1. Roll two six-sided random dice for the first time, getting a 1 and a 4.

3
2. Add the values on the top of the two dice, getting 5.
3. The value is not 2, 3, 7, 11, or 12, so the game continues.
4. Roll the two dice again, getting a 3 and a 6.

PART 3: Generalizing Into Pseudocode

Task
Write out the general sequence your program will use, including all specific examples/scenarios you
provided in Part 2.

Requirements
● Write pseudocode for the program in English but refer to Java program elements where they
are appropriate. The pseudocode should represent the full functionality of the program, not
just a simplified version. Pseudocode is broken down enough that the details of the program
are no longer in any paragraph form. One statement per line is ideal.

Help With Writing Pseudocode


● Here are a few links that can help you write pseudocode with examples. Remember to check
out part 3 of the Example Journal Template Submission if you have not already. Note:
everyone will write pseudocode differently. There is no right or wrong way to write it, other
than to make sure you write it clearly and in as much detail as you can so that it should be
easy to convert to code later.
○ https://www.geeksforgeeks.org/how-to-write-a-pseudo-code/
○ https://www.wikihow.com/Write-Pseudocode

Inspiration
When writing your entry below, ask yourself the following questions:
● Do you see common program elements and patterns in your specific examples/scenarios in
Part 2, like variables, conditionals, functions, loops, and classes? These should be part of
your pseudocode for the general sequence as well.
● Are there places where the steps for your examples/scenarios in Part 2 diverged? These may
be places where errors may occur later in the project. Make note of them.
● When you are finished with your pseudocode, does it make sense, even to a person that does
not know Java? Aim for the clearest description of the steps, as this will make it easier to
convert into program code later.

4
Function play()
Set the rolled value to roll first dice + roll second dice
If the rolled value is equal to 2, 3 or 12
Set player status to lose
Else If the rolled value is equal to 7 or 11
Set player status to win
Else
Set point value to rolled value
While the player status is not set, run the following
Set the rolled value to roll first dice + roll second dice
If the rolled value is equal to 7
Set player status to lose
Else If rolled value is equal to point value
Set player status to win

Main Program
Set Wins = 0
Set Losses = 0
Set Total of Win Rolls = 0
Set Total of Loss Rolls = 0
Set Games Played to 0

Input Times to Play from user


Loop until Games Played = Times to Play
Add 1 to Games Played
Call function play()
Get if the player won or lost
Get the number of rolls
If the player won
Add 1 to Wins
Else if player lost
Add 1 to Losses

Average Number of Rolls Per Win = Total of Win Rolls / Wins


Average Number of Rolls Per Loss = Total of Loss Rolls / Loss
Winning Percentage = Wins / Games Played
Output results

5
PART 4: Testing Your Program

Task
While writing and testing your program code, describe your tests, record any errors, and state your
approach to fixing the errors.

Requirements
● For at least one of your test cases, describe how your choices for the test helped you
understand whether the program was running correctly or not.
For each error that occurs while writing and testing your code:
● Record the details of the error from your IDE. A screenshot or copy-and-paste of the text into
the journal entry is acceptable.
● Describe what you attempted in order to fix the error. Clearly identify which approach was the
one that worked.

Inspiration
When writing your entry below, ask yourself the following questions:
● Have you tested edge cases and special cases for the inputs of your program code? Often
these unexpected values can cause errors in the operation of your program.
● Have you tested opportunities for user error? If a user is asked to provide an input, what
happens when they give the wrong type of input, like a letter instead of a number, or vice
versa?
● Did the outcome look the way you expected? Was it formatted correctly?

● Does your output align with the solution to the problem you coded for?

The first version of the code that handles the input of the number of games that the player wants to
play did not handle the input of characters that aren't digits correctly. The following screen shot
shows the problem:

6
Adding the following try and catch blocks to handle the InputMismatchException took care of the
messy error message:

try {
System.out.print("How many games would you like to play?: ");
numberOfGamesToPlay = input.nextInt();
// If previous statement doesn't throw exception, input valid
inputValid = true;
}
catch(InputMismatchException ex) {
System.out.println("Not a valid number.");
// Clear out input buffer
input.nextLine();
}

The game, though, did not run correctly and produced odd results, as shown below.

7
There isn't much point in displaying the statistics if the player hasn't been able to play any games
other than the sample game.

I was able to resolve this problem by adding a boolean variable named inputValid and initializing its
value to false. After that, introducing a while loop that runs as long as the input is not valid (the value
of inputValid is still false).

// Track if input of requested # of games to play is valid


boolean inputValid = false;
int numberOfGamesToPlay = 0;

// Assume invalid input of number until it proves to be correct


while(!inputValid) {
try {
System.out.print("How many games would you like to play?: ");
numberOfGamesToPlay = input.nextInt();

8
// If previous statement doesn't throw exception, input valid
inputValid = true;
}
catch(InputMismatchException ex) {
System.out.println("Not a valid number.");
// Clear out input buffer
input.nextLine();
}
}
System.out.println(); // Add blank line in output

The program runs correctly with these changes made. The full version of the code for the Craps class
(the driver class with the main() method now reads like this:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Scanner;
import java.util.ArrayList;
import java.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.util.InputMismatchException;

public class Craps {


public static void main(String[] args) {
// Variables for stats
int winCount = 0;
int lossCount = 0;
int rollCount = 0;

// Log file for player statistics


File logFile = new File("game.log.txt");

// Scanner to read player name & desired number of games


Scanner input = new Scanner(System.in);
System.out.print("Enter Player Name: ");
String playerName = input.nextLine();

// Run sample game first


System.out.println("\nRunning Sample Game: ");
Game game = new Game(playerName);
// ArrayList to track roles of dice in a game
ArrayList<DiceRoll> rolls = game.play();

9
for(DiceRoll roll : rolls) {
System.out.println("\t" + roll);
}
System.out.println("\nResult of Sample Game: " + game.getResult() + " in " +
game.getRollCount() + " roll(s)\n");
System.out.println();

// Track if input of requested # of games to play is valid


boolean inputValid = false;
int numberOfGamesToPlay = 0;

// Assume invalid input of number until it proves to be correct


while(!inputValid) {
try {
System.out.print("How many games would you like to play?: ");
numberOfGamesToPlay = input.nextInt();
// If previous statement doesn't throw exception, input valid
inputValid = true;
}
catch(InputMismatchException ex) {
System.out.println("Not a valid number.");
// Clear out input to remove \n
input.nextLine();
}
}
System.out.println(); // Add blank line in output

// Loop to play desired number of games


for(int i = 0; i < numberOfGamesToPlay; i++) {
game = new Game(playerName);
// Need to use parentheses so value is calculated before concatenation
System.out.println("Game " + (i + 1) + ":");
rolls = game.play();
rollCount += game.getRollCount();
for(DiceRoll roll : rolls) {
System.out.println("\t" + roll);
}
if(game.getResult().equals("Win")) {
winCount++;
}
else {
lossCount++;
}
System.out.println("\nResult: " + game.getResult() + " in " +

10
game.getRollCount() + " roll(s)\n");
}

// Compose String with summary statistics


String summary = "Statistics for " + game.getPlayerName() + ": " + "\n";
String gameDateTimeFormatString = "MM/dd/YYYY HH:mm:ss\n";
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern(gameDateTimeFormatString);
summary += "Game Date & Time: ";
summary += dateTimeFormatter.format(game.getGameDateTime());
summary += "# of Games: " + numberOfGamesToPlay + "\n";
summary += "# of Dice Rolls: " + rollCount + "\n";
summary += "# of Wins: " + winCount + "\n";
summary += "# of Losses: " + lossCount + "\n";
DecimalFormat percentageFormat = new DecimalFormat("0.00%");
double winPercentage = (double) winCount / numberOfGamesToPlay;
summary += "% Wins: " + percentageFormat.format(winPercentage) + "\n\n";

// Display statistics on screen


System.out.println(summary);

// Write statistics to log file


try {
// Create log file if it doesn't exist and then append to it.
Files.writeString(logFile.toPath(), summary, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
}
catch(IOException ex) {
System.out.println("Error writing to log file: " + ex.getMessage());
}
}
}

PART 5: Commenting Your Program

Task
Submit your full program code, including thorough comments describing what each portion of the
program should do when working correctly.

Requirements
● The purpose of the program and each of its parts should be clear to a reader that does not

11
know the Java programming language.

Inspiration
When writing your entry, you are encouraged to consider the following:
● Is each section or sub-section of your code commented to describe what the code is doing?

● Give your code with comments to a friend or family member to review. Add additional
comments to spots that confuse them to make it clearer.

DiceRoll Class

import java.util.Random;

public class DiceRoll {


// Array with 2 elements to hold rolls of 2 dice
private final int[] die = new int[2];
// Sum of the 2 dice
private int sum;
// Random number generator from java.util library
private Random randomNumberGenerator;

public DiceRoll() {
// Create random number generator
randomNumberGenerator = new Random();
// Argument of 6 means generator will produce a # in the range 0 - 5
// + 1 adjusts the result to be in the range from 1 to 6
die[0] = randomNumberGenerator.nextInt(6) + 1;
die[1] = randomNumberGenerator.nextInt(6) + 1;
sum = die[0] + die[1];
}

// Accessor method to get total of the 2 dice


public int getSum() { return sum; }

// Method to produce a String representation of the dice roll


public String toString() {
return "Dice: " + die[0] + " " + die[1] + " Sum = " + sum;
}
}

Game Class

12
import java.time.LocalDateTime;
import java.util.ArrayList;

public class Game {


private String playerName = "";
private LocalDateTime gameDateTime;
// ArrayList to hold dice rolls for player
private ArrayList<DiceRoll> diceRolls;

private int point = 0;


private boolean keepRolling = true;
// String to hold game result msg: "Win" or "Lose"
private String gameResult = "";

// Constructor to create Game object. Player name as String parameter


public Game(String playerName) {
gameDateTime = LocalDateTime.now();
this.playerName = playerName;
diceRolls = new ArrayList<DiceRoll>();
}

// Carry out dice rolls to play game.


public ArrayList<DiceRoll> play() {
// 1st roll for player
DiceRoll roll = new DiceRoll();
diceRolls.add(roll);
int sum = roll.getSum();

// Check for "craps" & resulting loss


if(sum == 2 || sum == 3 || sum == 12) {
gameResult = "Lose";
keepRolling = false;
}

// Check for immediate win


else if(sum == 7 || sum == 11) {
gameResult = "Win";
keepRolling = false;
}
else {
// Sum of dice is now player's "point"
point = roll.getSum();
}

13
// Loop for subsequent rolls
while(keepRolling) {
roll = new DiceRoll();
diceRolls.add(roll);
if(roll.getSum() == 7) {
gameResult = "Lose";
keepRolling = false;
}
else if(roll.getSum() == point) {
gameResult = "Win";
keepRolling = false;
}
}
// play() returns ArrayList of DiceRoll objects that make up the game
return diceRolls;
}

// Get String indicating result ("Win" or "Lose")


public String getResult() {
return gameResult;
}

// Get the number of dice rolls for game


public int getRollCount() {
// Number of DiceRoll objects in the ArrayList is number of rolls
return diceRolls.size();
}

public String getPlayerName() {


return playerName;
}

public LocalDateTime getGameDateTime() {


return gameDateTime;
}
}

Craps Class (Application's Driver Class)

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;

14
import java.util.Scanner;
import java.util.ArrayList;
import java.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.util.InputMismatchException;

public class Craps {


public static void main(String[] args) {
// Variables for stats
int winCount = 0;
int lossCount = 0;
int rollCount = 0;

// Log file for player statistics


File logFile = new File("game.log.txt");

// Scanner to read player name & desired number of games


Scanner input = new Scanner(System.in);
System.out.print("Enter Player Name: ");
String playerName = input.nextLine();

// Run sample game first


System.out.println("\nRunning Sample Game: ");
Game game = new Game(playerName);
// ArrayList to track roles of dice in a game
ArrayList<DiceRoll> rolls = game.play();
for(DiceRoll roll : rolls) {
System.out.println("\t" + roll);
}
System.out.println("\nResult of Sample Game: " + game.getResult() + " in " +
game.getRollCount() + " roll(s)\n");
System.out.println();

// Track if input of requested # of games to play is valid


boolean inputValid = false;
int numberOfGamesToPlay = 0;

// Assume invalid input of number until it proves to be correct


while(!inputValid) {
try {
System.out.print("How many games would you like to play?: ");
numberOfGamesToPlay = input.nextInt();
// If previous statement doesn't throw exception, input valid
inputValid = true;

15
}
catch(InputMismatchException ex) {
System.out.println("Not a valid number.");
// Clear out input to remove \n
input.nextLine();
}
}
System.out.println(); // Add blank line in output

// Loop to play desired number of games


for(int i = 0; i < numberOfGamesToPlay; i++) {
game = new Game(playerName);
// Need to use parentheses so value is calculated before concatenation
System.out.println("Game " + (i + 1) + ":");
rolls = game.play();
rollCount += game.getRollCount();
for(DiceRoll roll : rolls) {
System.out.println("\t" + roll);
}
if(game.getResult().equals("Win")) {
winCount++;
}
else {
lossCount++;
}
System.out.println("\nResult: " + game.getResult() + " in " +
game.getRollCount() + " roll(s)\n");
}

// Compose String with summary statistics


String summary = "Statistics for " + game.getPlayerName() + ": " + "\n";
String gameDateTimeFormatString = "MM/dd/YYYY HH:mm:ss\n";
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern(gameDateTimeFormatString);
summary += "Game Date & Time: ";
summary += dateTimeFormatter.format(game.getGameDateTime());
summary += "# of Games: " + numberOfGamesToPlay + "\n";
summary += "# of Dice Rolls: " + rollCount + "\n";
summary += "# of Wins: " + winCount + "\n";
summary += "# of Losses: " + lossCount + "\n";
DecimalFormat percentageFormat = new DecimalFormat("0.00%");
double winPercentage = (double) winCount / numberOfGamesToPlay;
summary += "% Wins: " + percentageFormat.format(winPercentage) + "\n\n";

16
// Display statistics on screen
System.out.println(summary);

// Write statistics to log file


try {
// Create log file if it doesn't exist and then append to it.
Files.writeString(logFile.toPath(), summary, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
}
catch(IOException ex) {
System.out.println("Error writing to log file: " + ex.getMessage());
}
}
}

PART 6: Your Completed Program

Task
Provide the IDE share link to your full program code.

Requirements
● The program must work correctly with all the comments included in the program.

Inspiration
● Check before submitting your Touchstone that your final version of the program is running
successfully.

https://onlinegdb.com/oVugPTdKWb

17

You might also like