Question

Java code tasks: Please help with a single class (class Coord) in this program. This project...

Java code tasks: Please help with a single class (class Coord) in this program. This project is called Panic! We will describe a single-level floorplan of a building, filled with different kinds of people and different kinds of threats. We will simulate how the people seek to evacuate the building to safety, and how the threats spread throughout the building. Various events will be announced, such as person movements, threats spawning, and people reaching safety or succumbing to the threats. We will read a map representation from a file, and we will write the messages to either a file or just System.out as directed.

class Coord

Our maps are represented in grid form, with each spot having a row/column coordinate. We store those numbers in a Coord object and provide some methods for convenient interaction.

Fields

public final int r, c

Methods

public Coord (int r, int c). Constructor, assigns both fields.

public Coord step(Direction d). What is the Coordinate one step in the given direction? Creates and returns this new Coord value. Note, it may or may not be on a particular Map. No error checking is performed here (we don't have access to the Map to check its dimensions).

public Coord copy(). Creates and returns a new Coord value with the same row/column representation as the current object.

public boolean equals(Object o). Given another object, is it also a Coord with the same row and column values?

public boolean adjacent(Coord other). Is the given other Coord exactly one spot away (N, E, S, W)? Only four locations can return true; all others (including the same location itself) would return false.

public String toString(). Representation of an @ symbol and the row/column values in parentheses, like this example in row 2, column 3: "@(2,3)" .

---------Tester cases-------

import org.junit.*;
import org.junit.Test;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;
import java.util.*;

public class CoordTests {
public static void main(String args[]){
org.junit.runner.JUnitCore.main("CoordTests");
}
  
// 1 second max per method tested
@Rule public Timeout globalTimeout = Timeout.seconds(1);
  
// Coord class
@Test public void coord1() { assertEquals(3, new Coord(3,4).r); }
@Test public void coord2() { assertEquals(4, new Coord(3,4).c); }
  
Coord c = new Coord (5,10);
  
// check each step direction.
@Test public void coord3() {
assertEquals( 4, c.step(Direction.N).r);
assertEquals(10, c.step(Direction.N).c);
}
@Test public void coord4() {
assertEquals( 5, c.step(Direction.E).r);
assertEquals(11, c.step(Direction.E).c);
}
@Test public void coord5() {
assertEquals( 6, c.step(Direction.S).r);
assertEquals(10, c.step(Direction.S).c);
}
@Test public void coord6() {
assertEquals( 5, c.step(Direction.W).r);
assertEquals( 9, c.step(Direction.W).c);
}
  
@Test public void coord7() {
// check all manner of copying:
// same fields
assertEquals(c.r, c.copy().r);
assertEquals(c.c, c.copy().c);
// not an alias
assertFalse(c==c.copy());
}  
  
@Test public void coord8() {
// equals()
assertEquals(c, c.copy());
assertEquals(c, c);
assertFalse(c.equals(new Coord (2,3))); // @(5,10) != @(2,3).
assertFalse(c.equals("hello")); // must work for non-Coords.
}
  
@Test public void coord9() {
// we are adjacent in cardinal directions.
assertTrue(c.adjacent(new Coord(4,10)));
assertTrue(c.adjacent(new Coord(6,10)));
assertTrue(c.adjacent(new Coord(5,11)));
assertTrue(c.adjacent(new Coord(5, 9)));   
}  
@Test public void coord() {
// we are not adjacent diagonally.
assertFalse(c.adjacent(new Coord(4, 9)));
assertFalse(c.adjacent(new Coord(6, 9)));
assertFalse(c.adjacent(new Coord(4,11)));
assertFalse(c.adjacent(new Coord(6,11)));
}
@Test public void coord10(){
// we are not adjacent to ones further away.
assertFalse(c.adjacent(new Coord(3,10)));
assertFalse(c.adjacent(new Coord(7,10)));
assertFalse(c.adjacent(new Coord(5, 8)));
assertFalse(c.adjacent(new Coord(5,12)));
  
assertFalse(c.adjacent(new Coord(30,50)));
assertFalse(c.adjacent(new Coord( 0, 0)));
assertFalse(c.adjacent(new Coord(10,10)));
assertFalse(c.adjacent(new Coord( 5, 5)));
}
  
}

Thank you.

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

Hello, I have a solution for you. Implemented everything as per the requirements.

  1. Completed the class Coord.java with all the required methods and attributes, explained by well defined comments in every steps.
  2. Defined the Direction enum java file as you have not provided one.
  3. Executed the test class and satisfied 11/11 test cases.
  4. If you have any doubts, feel free to ask, Thanks

//Coord.java

public class Coord {

                // attributes

                public final int r, c;

                // parameterized constructor

                public Coord(int r, int c) {

                                this.r = r;

                                this.c = c;

                }

                /**

                * method to find the Coordinate one step in the given direction

                */

                public Coord step(Direction d) {

                                int newRow = r, newCol = c;

                                if (d == Direction.N) {

                                                // previous row

                                                newRow = r - 1;

                                } else if (d == Direction.S) {

                                                // next row

                                                newRow = r + 1;

                                }

                                if (d == Direction.E) {

                                                // next col

                                                newCol = c + 1;

                                } else if (d == Direction.W) {

                                                // prev col

                                                newCol = c - 1;

                                }

                                // creating a Coord with new row and col values

                                Coord coord = new Coord(newRow, newCol);

                                return coord;

                }

                /**

                * Creates and returns a new Coord value with the same row/column

                */

                public Coord copy() {

                                Coord coord = new Coord(r, c);

                                return coord;

                }

                /**

                * given another object, checks if it is also a Coord object with the same

                * row and column values

                */

                public boolean equals(Object o) {

                                if (o instanceof Coord) {

                                                Coord coord = (Coord) o; // safe type casting

                                                if (coord.r == r && coord.c == c) {

                                                                return true;

                                                }

                                }

                                return false;

                }

                /**

                * checks if the given other Coord exactly one spot away (N, E, S, W)?

                */

                public boolean adjacent(Coord other) {

                                if (this.step(Direction.N).equals(other)) {

                                                //one step to the north

                                                return true;

                                }

                                if (this.step(Direction.E).equals(other)) {

                                                //one step to the east

                                                return true;

                                }

                                if (this.step(Direction.S).equals(other)) {

                                                //one step to the south

                                                return true;

                                }

                                if (this.step(Direction.W).equals(other)) {

                                                //one step to the W

                                                return true;

                                }

                                return false;

                }

                @Override

                public String toString() {

                                return String.format("@(%d,%d)", r, c);

                }

}

// Direction.java

public enum Direction {

                //all four directions

                N, E, S, W

}

/*OUTPUT*/


Runs: 11/11 Errors: 0 Failures: 0 coords.CoordTests [Runner: JUnit 4] (0.015 s) coord1 (0.000 s) coord2 (0.000 s) coord3 (0.0

Add a comment
Know the answer?
Add Answer to:
Java code tasks: Please help with a single class (class Coord) in this program. This project...
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
  • Please help complete the items marked TODO in the code and get the tests to pass:...

    Please help complete the items marked TODO in the code and get the tests to pass: import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestIterator { private List<Integer> list; // See the Java List Interface documentation to understand what all the List methods do ... @Before public void setUp() throws Exception { list = new ArrayList<Integer>(); // TODO also try with a...

  • In Java, you'll find that it contains several methods that have not yet been finished. For now, the methods contain...

    In Java, you'll find that it contains several methods that have not yet been finished. For now, the methods contain only a placeholder return value so that the code will compile. Fill in your own implementation. public class SomePracticeStringMethods { /* * returns true if c is a letter in the word "temple" or false otherwise */ public static boolean inTU(char c) { /* placeholder just so that the function * compiles. fill in your implementation here. * * there...

  • Need help with a number guessing game in java 1) You should store prior guessses in...

    Need help with a number guessing game in java 1) You should store prior guessses in a linked list, and the nodes in the list must follow the order of prior guesses. For example, if the prior guesses are 1000, 2111, 3222 in that order, the nodes must follow the same order 2) You should store the candidate numbers also in a linked list, and the nodes must follow the order of numbers (i.e. from the smallest to the largest)....

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • I am not passing some of the code when i run the testing . PriorityQueue public...

    I am not passing some of the code when i run the testing . PriorityQueue public class PriorityQueue<T extends Comparable<T>> implements IPriorityQueue<T> {    private Vector<T> theVector = new Vector<>(0, 1);    private int size = 0;    @Override    public void insert(T element) {        theVector.pushBack(element);        size++;        bubbleUp(); }    @Override    public T peekTop() throws java.util.NoSuchElementException {        if (isEmpty()) {            throw new java.util.NoSuchElementException();        }       ...

  • JAVA Only Help on the sections that say Student provide code. The student Provide code has...

    JAVA Only Help on the sections that say Student provide code. The student Provide code has comments that i put to state what i need help with. import java.util.Scanner; public class TicTacToe {     private final int BOARDSIZE = 3; // size of the board     private enum Status { WIN, DRAW, CONTINUE }; // game states     private char[][] board; // board representation     private boolean firstPlayer; // whether it's player 1's move     private boolean gameOver; // whether...

  • Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections;...

    Please use my code to implement the above instructions. My Grid class: import java.util.ArrayList; import java.util.Collections; class Grid { private boolean bombGrid[][]; private int countGrid[][]; private int numRows; private int numColumns; private int numBombs; public Grid() { this(10, 10, 25); }    public Grid(int rows, int columns) { this(rows, columns, 25); }    public Grid(int rows, int columns, int numBombs) { this.numRows = rows; this.numColumns = columns; this.numBombs = numBombs; createBombGrid(); createCountGrid(); }    public int getNumRows() { return numRows;...

  • Write a class called RationalNumber that represents a fraction with an integer numerator and denominator. A...

    Write a class called RationalNumber that represents a fraction with an integer numerator and denominator. A RationalNumber object should have the following methods: public RationalNumber(int numerator, int denominator) Constructs a new rational number to represent the ratio (numerator/denominator). The denominator cannot be 0, so throw an IllegalArgumentException if 0 is passed. public RationalNumber() Constructs a new rational number to represent the ratio (0/1). public int getDenominator() Returns this rational number’s denominator value; for example, if the ratio is (3/5), returns...

  • Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static...

    Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static String solve(char[][] grid) {        // TODO        /*        * 1. Construct a graph using grid        * 2. Use BFS to find shortest path from start to finish        * 3. Return the sequence of moves to get from start to finish        */               // Hardcoded solution to toyTest        return...

  • Fix this program package chapter8_Test; import java.util.Scanner; public class Chapter8 { public static void main(String[] args)...

    Fix this program package chapter8_Test; import java.util.Scanner; public class Chapter8 { public static void main(String[] args) { int[] matrix = {{1,2},{3,4},{5,6},{7,8}}; int columnChoice; int columnTotal = 0; double columnAverage = 0; Scanner input = new Scanner(System.in); System.out.print("Which column would you like to average (1 or 2)? "); columnChoice = input.nextInt(); for(int row = 0;row < matrix.length;++row) { columnTotal += matrix[row][columnChoice]; } columnAverage = columnTotal / (float) matrix.length; System.out.printf("\nThe average of column %d is %.2f\n", columnAverage, columnAverage); } } This program...

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