You are on page 1of 12

Week 10 Homework

Problem 1
Write a main method class that prompts the user to enter a string
value. Complete as indicated below in each section.
Part 1 (3 points)
Using a while loop, prompt the user 10 times to enter a string value.
Store the values entered in an array. After the values have been
entered and stored, write a second while loop to read through the
values, displaying them to the console in the order which they were
entered. Write a third while loop to read through the values,
displaying them to the console in reverse order.
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Week10Prob1 {
public static void main(String[] args) {
String myArr[] = new String[10];
int myTries = 10;
int myInput = 0;
Scanner myScan = new Scanner(System.in);
String scanInput;
while(myInput < myTries){

System.out.println("Enter a single word: ");


scanInput = myScan.nextLine();
myArr[myInput] = scanInput;
myInput++;

System.out.println(" ");
while (myTries == 10){
System.out.println("Here are your words in order:");
Arrays.sort(myArr);
for (String str : myArr){
System.out.println(str);
}
break;
}
System.out.println(" ");
while (myTries == 10){
System.out.println("Here are your words in reverse order:");
Arrays.sort(myArr, Collections.reverseOrder());

Week 10 Homework

for (String str : myArr){


System.out.println(str);
}
break;

}
}

Week 10 Homework

Part 2 (3 points)
Rewrite your code from Part 1, replacing each of the while loops with
a for loop and replacing the array with an array list.
import
import
import
import

java.util.ArrayList;
java.util.Arrays;
java.util.Collections;
java.util.Scanner;

public class Week10Prob1 {


public static void main(String[] args) {

ArrayList<String> myArr = new ArrayList<String>();


Scanner myScan = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.println("Enter a single word: ");
String inPut = myScan.nextLine();
myArr.add(inPut);
}
System.out.println("Here are your words in order:");
for (int i = 0; i < myArr.size(); i++){
Collections.sort(myArr);
System.out.println(myArr.get(i));
}
System.out.println(" ");
System.out.println("Here are your words in reverse:");
for (int i = 0; i < myArr.size(); i++){
Collections.sort(myArr, Collections.reverseOrder());
System.out.println(myArr.get(i));
}
}
}

Week 10 Homework

Part 3 (1 point)
Rewrite your code from Part 2 above, replacing the last two for loops
the loops used to display the values of the array list, with an
enhanced for loop.
import
import
import
import

java.util.ArrayList;
java.util.Arrays;
java.util.Collections;
java.util.Scanner;

public class Week10Prob1 {


public static void main(String[] args) {

ArrayList<String> myArr = new ArrayList<String>();


Scanner myScan = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.println("Enter a single word: ");
String inPut = myScan.nextLine();
myArr.add(inPut);
}
System.out.println("Here are the words in the array:");
for (String myForArr : myArr){
System.out.println(myForArr);
}

}
}

Week 10 Homework

Problem 4 Battleship
BattleShip is a game where ships are hidden in an ocean and
are then searched for using coordinates. In our game, the
ocean will be represented by a matrix of data type char. A
hidden ship is represented by the char value X. A found ship
is represented by the char value B. An unsearched coordinate
in the ocean is represented by the char value .. A searched
coordinate in the ocean is represented by the char value ~.
The matrix could be any size, 2x2, 3x3, 10x10, 20x20, etc.
An example would be: (DO NOT code for the example, just use
as reference)
0
1
2

0
.
B
X

1
.
~
~

2
X
X
X

The . in position 0,0 indicates that this position does not


contain a ship and it has not yet been search.
The B in position 1,0 indicates that it has been search and
it contains a ship.
The X in position 2,0 indicates that it has not been search
and it contains a ship.
The ~ in position 1,1 indicates that it has been searched
and it does not contain a ship.

Week 10 Homework

Part 1 Test Case (2 points)


Write test cases for the following constructor and method:
BattleShip(char[][] inOcean)
This constructor creates a BattleShip object. It accepts
one expicit constructor, a matrix consisting of char
objects. You will need to build an object and pass it to the
constructor and then test to make sure the object has
been successfully created (not null).
boolean isHit(int row, int col)
This method returns true if a ship is found at the specified
coordinate. If a ship is found, the X at the position is
changed from an X to a B. It returns false if a ship is not
found at the specified coordinate. If a ship is not found,
the . at the position is changed from . to ~.
I DIDNT HAVE TIME FOR THIS. I PUT SOMETHING
TOGETHER REALLY QUICK
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class BattleShipTest {
@Test
public void testBattleShip()
{
BattleShip myBattle = new BattleShip();
char[][] ocean = new char[4][4];
//myBattle.BattleShip(ocean);
assertNotNull(myBattle);
assertEquals(ocean, myBattle.BattleShip(ocean));
}

@Test
public void testIsHit()
{
BattleShip myBattle = new BattleShip();
myBattle.isHit(0, 0);
assertEquals(true, myBattle.isHit(0,0));
myBattle.isHit(0, 1);

Week 10 Homework

assertEquals(false, myBattle.isHit(0,0));
}

Week 10 Homework

Part 2 BattleShip Class (3 points)


Write the BattleShip Class with the following methods:
Instance variable matrix of data type char, do not specify a
size. This will be determined by the matrix passed to the
constructor.
BattleShip(char[][] inOcean)
This constructor creates a BattleShip object. It accepts
one expicit constructor, a matrix consisting of char
objects. Set the matrix instance variable to the passed in
explicit parameter.
boolean isHit(int row, int col)
This method returns true if a ship is found at the
specified coordinate. If a ship is found, the X at the
position is changed from an X to a B.
It returns false if a ship is not found at the specified
coordinate. If a ship is not found, the . at the position
is changed from . to ~.
String toString()
Build a string containing the matrix.
The first row should contain the column labels of each
column. Skip the first column as this will contain the
row labels.
The first column should contain the row labels of each
row.
If a position in the matrix contains a X, display . to
show it has not yet been searched.
If all of the ships have been found (no Xs in the
matrix), display WINNER: All ships have been found.
To have equal spacing when printing the matrix use \t
to tab between elements and \n at the end of each
row to start a new row.
If the matrix consists of:
0
1
2

Week 10 Homework

0
.
B
X

1
.
~
~

2
X
X
X

The string returned should contain:


0
1
2

0
.
B
.

1
.
~
~

2
.
.
.

public class BattleShip {


// Variable
char[][] ocean = new char[4][4];

{
}

public void BattleShip(char[][] inOcean)


this.ocean = inOcean;

public boolean isHit(int row, int col)


{
boolean myResult;
if ( (row > this.ocean.length) ||
(col > this.ocean[row].length)) {
return false;
}
if ( ocean[row][col] == 'X' ) {
this.ocean[row][col] = 'B';
myResult = true;
} else if (ocean[row][col] == '.' ) {
this.ocean[row][col] = '~';
myResult = false;
} else {
myResult = false;
}
return myResult;
}

public String toString()

int numberOfX = 0;
String boardOut = " ";
for ( int i = 0; i < this.ocean[0].length; i++) {
boardOut = boardOut + "\t" + i;
}
boardOut = boardOut + "\n";

Week 10 Homework

for ( int i = 0; i < this.ocean[0].length; i++) {


boardOut = boardOut + i;
for ( int j = 0; j < this.ocean[i].length; j++) {
if ( this.ocean[i][j] == 'X' ) {
boardOut = boardOut + "\t.";
numberOfX++;
} else {
boardOut = boardOut + "\t" + this.ocean[i][j];
}
}
boardOut = boardOut + "\n";
}

if (numberOfX == 0) {
boardOut = boardOut + "All ships have been found - AWESOME.";
}
return boardOut;

Part 3 BattleShipDriver Class (3 points)


Write the BattleShipDriver Class to do the following:
Build a char matrix of any size
o Populate the matrix with . and X where .
indicates an empty position and X indicates a
hidden ship.
Use the BattleShip class written in Part 2
Construct a Battleship object, passing your matrix as the
explicit parameter
Display the BattleShip object matrix
In a loop:
o Continue looping until sentinel value is entered
o Prompt the user to enter a row coordinate
o Prompt the user to enter a column
o Check to see if the entered coordinates are a hit
If they are a hit display HIT
If they are not a hit display MISS
o Display the matrix

import java.util.Scanner;
public class BattleShipDriver {
public static void main(String[] args)throws java.lang.Exception {

Week 10 Homework

10

Scanner myScan = new Scanner(System.in);


int myRShot;
int myCShot;
BattleShip myBattle = new BattleShip();
System.out.println("Let's play some BattleShip!");
System.out.println(" ");
System.out.println("'.' stands for unsearched water.");
System.out.println("'~' stands for searched water.");
System.out.println("'B' means you hit a ship!");
System.out.println(" ");
System.out.println(" ");
System.out.println("HAVE FUN!!!");
System.out.println(" ");
System.out.println(" ");
char[][] ocean = {
{
{
{
{

'X', '.', '.', 'X'},


'.', '.', 'X', '.'},
'.', 'X', '.', '.'},
'.', '.', '.', 'X'}

};
myBattle.BattleShip(ocean);
System.out.println(myBattle.toString());
boolean startGame = true;
while(startGame){
System.out.print("Enter a row number: ");
myRShot = myScan.nextInt();
System.out.print("Enter a column number: ");
myCShot = myScan.nextInt();

if (myBattle.isHit(myRShot, myCShot) == true){


System.out.println(" ");
System.out.println("YES!!! YOU GOT ONE!!!!");
System.out.println(" ");
}else {
System.out.println(" ");
System.out.println("WHOOPS - YOU MISSED! TRY
AGAIN.");

Week 10 Homework

System.out.println(" ");
}
System.out.println(myBattle.toString());

11

if (myBattle.toString().contains("All")){
startGame = false;
}
}

}
}

Week 10 Homework

12

You might also like