Question

Advanced Object-Oriented Programming using Java
Assignment 4: Exception Handling and Testing in Java

Introduction -  This assignment is meant to introduce you to design and implementation of exceptions in an object-oriented language. It will also give you experience in testing an object-oriented support class.

You will be designing and implementing a version of the game Nim. Specifically, you will design and implement a NimGame support class that stores all actual information about the state of the game, and detects and throws exceptions when problems occur.

Basic Rules of Nim -  Most versions of the game Nim involves 3 rows of “sticks”. For example:

| | |

| | | | |

| | | | | | |

Players alternate turns, each removing between 1 and 3 sticks from some row of their choice. For example, if player 1 takes 3 sticks from row 2, the board will then look like:
| | |

| |

| | | | | | |

Of course, a player cannot take more sticks from a row than there are left. For example, a player cannot remove 3 sticks from row 2 of the above board.

The game continues until some player is forced to take the last stick, leaving none on the board. That player loses.
In your application, a human player will alternate moves with a “computer” player. To simplify things, the computer player will choose a random number of sticks (between 1 and 3) from a random row. Of course, the number of sticks removed must be legal.

The NimGame Support Class - Required Constructors and Methods:

Your NimGame support class is required to have the following constructors and methods:

(1) public NimGame(int[] initialSticks) - This constructor should create a new game with the initial number of sticks in each row set to the corresponding elements of initialSticks.

For example, to create a game with initially 3, 5, and 7 sticks, this would be called as
new NimGame(new int[]{3, 5, 7});

(2) public int getRow(int r) - This inspector method returns the current number of sticks in row r.
Note that the user will enter a number between 1 and 3, not between 0 and 2 (this is more user friendly).

(3) public void play(int r, int s) - This modifier method should remove s sticks from row r. Again, note that the user will enter a number between 1 and 3 for the row.

It should also do validation on the number of sticks, throwing one of the following exceptions if the number of sticks, returning the following exceptions:

(a) NoSuchRowException if the row is not between 1 and 3.

(b) IllegalSticksException if the number of sticks taken is not between 1 and 3.

(c) NotEnoughSticksException if the number of sticks taken is between 1 and 3, but more than the number of sticks remaining in that row.

(4) public boolean isOver() - This inspector returns true if there are no sticks left in any row, false otherwise.

(5) public void AIMove() - This modifier takes a random number of sticks (between 1 and 3) from a random row, in order to make the computer’s move.

- Note that this must also do validation, making sure that it does not take more sticks than there are left in a row. A simple way to do this is “generate and test”:

while (not enough sticks in that row) {
    generate a random row and number of sticks
}

(6) public String toString() - This should return the “state” of the object (that is, the number of sticks in each row) as a string.
- Note that it is not used in the visual application, but will be used for the JUnit testing described below.

IMPORTANT DESIGN NOTE:  Your NimGame methods will only throw exceptions. They will not be catching any exceptions. All exceptions will be caught within the actionPerformed method of the NimApp class.

Designing Additional Exceptions - The above situations are not the only in which an exception can occur. You are to look over your NimGame class methods and constructors and identify at least two other instances where it would be appropriate for an exception to be thrown. This is the main design exercise of this assignment.

In each case, create an appropriate exception class, and modify the code to throw the exception if it occurs.

The NimApp Application Class - I have provided a simple command line application called NimApp for running your support class. When run (with a working NimGame class), it looks like the following:

Test Results Output-3701 assignments (run) a Which row to remove sticks from: 2 How many sticks to remove: 3 AI makes move Which row to remove sticks from:

When the player enters the row and sticks, the application calls the play method and redraws the sticks by calling the getRow method for each row). It then calls the AIMove method to make the computer move, and then redraws the sticks again.

This continues until there are no more sticks (checked by isOver calling the method), at which point whoever made the last move loses:

Carefully examine the main method in the application to see how this works, particularly with respect to how the play method is called.

Handling NimGame Exceptions -  Note that there is currently no exception handling in this method. You are to modify this code to handle the three exceptions that may be thrown by the play method. In each case, it should pop up an appropriate error message. For example:

Also note that if the player makes an illegal move, it must remain their turn. That is, the AIMove method must not be called in that case. Hint: Think carefully about what code should be inside the try block.

Handling Other Exceptions - Aside from the exceptions thrown by the play method, there is one other type of exception that might be thrown in the main loop in this application due to player error. Add code to catch this exception and to display an appropriate message.

- HINT: When you play the game, think about what “unusual” input a player could try to enter.

Creating JUnit Testing Cases - Finally, you are to create a set of testing tools for your NimGame class using the JUnit testing tool.

To start, right-click the NimGame in NetBeans, and go to Tools à Create JUnit Tests. This will set up a file called NimGameTest under the Test Packages folder.

It will generate a test method for each of your methods. To simplify things, you are only required to create tests for the methods:

getRow

play

You can comment out the rest of the tests if you like.

Testing the getRow Method -  Since this will be easier, I suggest that you start with this one. Your tester will need to do the following (some of which is already built in):

(1) Construct an instance object of a NimGame.

(2) Call your getRow method for some row to determine whether it returns the correct number of sticks in that row.

Testing the play Method -  You are to provide two tests for this method:

(1) Taking a legal number of sticks from a legal row.

(2) Taking sticks from an illegal row.

Test Case for legal play -  Since this is a modifier, you will need to make sure the state has changed correctly. More specifically:

(1) Construct an instance object of a NimGame.

(2) Call the play method, with a legal row and number of sticks.

(3) Use your toString method to compare the expected state of the object to the actual state.

Test Case for illegal row -  Since your method will be expected to throw an exception if the player chooses an illegal row, the structure of these testing methods will be different:

(1) Construct an instance object of a NimGame.

(2) Inside a try block:

(a) Call the play method for some illegal row.

(b) Call fail (since we would have exited the block if an exception were thrown).

(3) Inside the catch block:

(a) Use your toString method to make sure the state of the game has not changed.

DOCUMENTATION -  Be sure to document the exception handling and testing components of your code. Specifically:

(1) Document each method of your NimGame class, particularly the sections related to detecting and throwing exceptions.
- NOTE THAT: You are to use Javadoc format for this.

(2) Document the changes you make to the main method related to handling the exceptions thrown by NimGame methods.

(3) Document the two testing methods you create in JUnit, describing what they are testing and how.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

package nimgame;

import java.util.Random;

public class NimGame {

    int[] board;

    public NimGame(int[] initialStick) {
        this.board = initialStick;
    }

    public int getRow(int r) {
        return board[r - 1];
    }

    public void play(int r, int s) {
        if (r >= 1 && r <= 3) {
            if (s >=1 && s <= 3) {

                if (getRow(r) >= s) {
                    board[r - 1] -= s;
                } else {
                    throw new NoEnoughSticksException("No Enough Sticks");
                }
            } else {
                throw new IllegalSticksException("Stick Should be between 1 and 3");
            }
        } else {
            throw new NoSuchRowException("No such row");
        }

    }

    public boolean isOver() {
        for (int x : board) {
            if (x > 0) {
                return false;
            }
        }
        return true;
    }

    public void AIMove() {
        boolean validMove = false;
        while (!validMove) {
            int s = new Random().nextInt(3) + 1;
            int r = new Random().nextInt(3);
            if (s >=1 && s <=3) {
                if (board[r] >= s) {
                    board[r] -= s;
                    validMove = true;
                    System.out.println("Computer move:" + (r+1) + " " + s);
                }
            }
        }
    }
}

package nimgame;

public class NoEnoughSticksException extends RuntimeException {
    public NoEnoughSticksException(String s) {
        super(s);
    }
}

package nimgame;

public class IllegalSticksException extends RuntimeException {
    public IllegalSticksException(String s) {
        super(s);
    }
}

package nimgame;

public class NoSuchRowException extends RuntimeException {
    public NoSuchRowException(String message) {
        super(message);
    }
}

package nimgame;

import java.util.Scanner;

public class Driver {

    public static void displayBoard(int []board){
        for(int x:board){
            for(int i=0;i<x;i++){
                System.out.print("|");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        NimGame nimGame = new NimGame(new int[]{3,5,7});
        Scanner sc = new Scanner(System.in);
        int row,sticks;
        while (true){
            displayBoard(nimGame.board);
            System.out.println("Player row and number od sticks(row,sticks):");
            row = sc.nextInt();
            sticks = sc.nextInt();
            try {
                nimGame.play(row,sticks);
                if(nimGame.isOver()){
                    System.out.println("Computer win !");
                    break;
                }
            }
            catch (NoSuchRowException e){
                System.out.println(e.getMessage());
                continue;
            }
            catch (NoEnoughSticksException e){
                System.out.println(e.getMessage());
                continue;
            }
            catch (IllegalSticksException e){
                System.out.println(e.getMessage());
                continue;
            }
            nimGame.AIMove();
            if(nimGame.isOver()){
                System.out.println("You win !");
                break;
            }


        }

    }
}

output:

IF ANY QUERIES REGARDING EXECUTION AND CODE PLEASE GET BACK TO ME

THANK YOU

Add a comment
Know the answer?
Add Answer to:
Advanced Object-Oriented Programming using Java Assignment 4: Exception Handling and Testing in Java Introduction -  This assignment...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Background: The purpose of this assignment is to practice dealing with exception handling and textual data....

    Background: The purpose of this assignment is to practice dealing with exception handling and textual data. Exception handling is a very important part of being an object-oriented programming. Rather returning some kind of int return value every time you tickle an object, C++ programmers expect methods to focus on their task at hand. If something bad happens, C++ programmers expect methods to throw exceptions. When caught, exceptions can be processed. When uncaught, they cause a program to terminate dead in...

  • Need help with Exception coding in JAVA

    The aims of this lab are: Understand the purpose of exception handlingHow to create your own exception class.Use of assertion1. Create a class TutorialSpace that used to enrol student in a tutorial class. It should have the following private attributes:slots — the number of available slots in a tutorial classactivated — true if the tutorial class has been activated and the following methods:TutorialSpace(n) — a constructor for a tutorial class with n slots. activate() — activates the tutorial class. Throws an exception if...

  • ****Here is the assignment **** Purpose: To write an Object-Oriented application that creates a Java class...

    ****Here is the assignment **** Purpose: To write an Object-Oriented application that creates a Java class with several instance variables, a constructor to initialize the instance variables, several methods to access and update the instance variables’ values, along with other methods to perform calculations. Also, write a test class that instantiates the first class and tests the class’s constructor and methods. Details: Create a class called Rectangle containing the following: Two instance variables, An instance variable of type double used...

  • C++ Your assignment this week is to make your fractionType class safe by using exception handling....

    C++ Your assignment this week is to make your fractionType class safe by using exception handling. Use exceptions so that your program handles the exceptions division by zero and invalid input. · An example of invalid input would be entering a fraction such as 7 / 0 or 6 / a · An example of division by zero would be: 1 / 2 / 0 / 3 Use a custom Exception class called fractionException. The class must inherit from exception...

  • Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions...

    Needs Help In Java Programming language Exceptional Cars Purpose To review interfaces and exception usage. Directions Your task is to write a class called Car. Your class should have the following fields and methods: private int position private boolean headlightsOn public Car() - a constructor which initializes position to 0 and headlightsOn to false public Car(int position) - a constructor which initializes position to the passed in value and headlightsOn to false, and it should throw a NegativeNumberException with a...

  • Java programming The purpose of this problem is to practice using a generic Urn class. NOTE:...

    Java programming The purpose of this problem is to practice using a generic Urn class. NOTE: Refer to the code for the ArrayStack class from Chapter 12. Use that code as a starting point to create the Urn class, modifying it to remove the methods in the ArrayStack class (push, pop, etc) then add the methods described below. Also change the variable names to reflect the new class. For example the array name should NOT be stack, instead it should...

  • Background: This assignment deals with inheritance. Inheritance is one of the major principles of object-oriented programming....

    Background: This assignment deals with inheritance. Inheritance is one of the major principles of object-oriented programming. In C++, one of the biggest goals is "code reuse". Inheritance accomplishes this. In order to get inheritance working in C++, you must get both the structure of your .h files as well as the implementation of your constructor correct. Constructor implementations must use an initialization list. Please review the book and the online content on these issues so you know how it works...

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • Source material: Object-Oriented Data Structures Using Java, 3rd Edition by Nell Dale. What is the answer...

    Source material: Object-Oriented Data Structures Using Java, 3rd Edition by Nell Dale. What is the answer to exercise 13 in chapter 3 (page 232)?? "A. Create a "standard" exception class called ThirteenException. B. Write a program that repeatedly prompts the user to enter a string. After each string is entered the program outputs the length of the string, unless the length of the string is 13, in which case the ThirteenException is thrown with the message "Use thirteen letter words...

  • *Python* INTRODUCTION: The goal of this programming assignment is to enable the student to practice object-oriented...

    *Python* INTRODUCTION: The goal of this programming assignment is to enable the student to practice object-oriented programming using classes to create objects. PROBLEM DEFINITION: Write a class named Employee that holds the following data about an employee in attributes: name, IDnumber, department, jobTitle The class should have 8 methods as follows:  For each attribute, there should be a method that takes a parameter to be assigned to the attribute. This is known as a mutator method.  For each...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT